How to Use Python List Comprehensions

LeMaster Tech
182 followers
Apr 20, 2025
List comprehensions are powerful python tools that can process and change lists and dictionaries in a single line of code!
Code used in this example can be found here: https://github.com/plemaster01/ListComprehensions
Consider Checking out my Patreon! https://www.patreon.com/LeMasterTech
welcome back to L Master Tech and in
today's video I'm going to show you how
to use an awesome and Powerful
programming tool in the Python
programming language called list
[Music]
comprehensions so if you've never seen
list comprehensions in python or maybe
you've seen them slard of them but
you've kind of avoided learning about
them because it seemed new and
unnecessary um you're missing out
because this is an awesome feature that
uh python has available to you and to
show you a basic list comprehension um
I'm going to use a pretty exam a pretty
good example of some basic python all
right so let's say that I have a list
and it comes in as all lowercase kind of
poorly formatted and it's a list of
names in this case just three names well
the conventional way to write python
code to capitalize all of those names
and then store them in another list or
even the same list would be code that
looks something like this so it would be
make a new list in this case we'd say
like names unor proper and then for I in
range of however many of those names
there are so if we added a fourth name
this code would not break it would still
be able to handle that um and then you
might have some if conditional maybe not
so in this case just to show the power
of list comprehensions I added if names
start with P so in that case I'm only
going to grab names that start with P so
it would be Pete and philli but not Dale
in this example um you don't need that
step obviously if you want to capitalize
all of the names you could just comment
that out and skip it but then you would
do two things you would capitalize each
name turn into uh a string transform
called tile this is a built-in python
function that um parses a string and
makes the first letter of each new word
after a space um a a capital and then
store that in the list of proper names
and so if I run this you'll see down in
the bottom I get all three names now
capitalized and nicely formatted um and
then to add back in the if conditional
let's say if we only want the ones that
start with a p and I run it again you'll
see now I get the same list still nicely
formatt and capitalized but just Pete
and Phillip not Dale this time and this
code is perfect valid and uh completely
functional in Python and probably
something very familiar to people with a
little bit of basic Python programming
experience but the incredibly powerful
uh abilities of list comprehensions come
in when we take a look at a way to
define this all in one line so the basic
format of a list comprehension is up
here in the comment new list equals a
for B in C if d and if D is optional but
so what does this mean let's take a look
at this example so names proper is going
to equal the actual value that we want
which would be each name turned into a
title four and then name because this is
just a variable that we're defining
think of like an indexer variable that
gets used in a for Loop so name. tile
for each name that is in the list names
and then we could stop right there uh
except that title needs those uh uh
parentheses um we could stop right there
and to show you what that's going to do
it goes back to giving us all three of
the uh original names and capitalized um
but we can go even one step further so
this is where I said that if condition D
is uh capitalized um or is optional um
then what we could say after this too is
if name Dot and then another buil in
Python string function which is do
starts with and then starts with the
letter P so now this if I run it is
going to give us just Pete and Phillip
capitalized nicely formatted and so this
is just one specific example obviously
there's not really a world where you
would badly need to take a list of three
names capitalize them and use a list
comprehension but this starts becoming
incredibly powerful in much larger data
sets and examples and maybe the
conventional python programmer in you
thinks like well this is a lot easier to
read you know if you're not familiar
with list comprehensions this is a
little bit of like syntax sugar and it
looks a little bit diff more difficult
to read here I know exactly what's
happening like I'm iterating through
however long my names list is I'm
checking to see if it starts with a p
and if it is I capitalize it using the
title function and then I add it to my
name's proper list but once you learn to
read a python list comprehension
this line of code is doing the exact
same thing it is taking each item inside
of this list it is storing it in a
variable called name and then it is
doing thetitle transform to that
variable and then it's checking just
like before to see if that variable if
that value starts with the letter P
so we have taken five lines of code here
and turned them into one line of code um
and strings and capitalizing things are
kind of just the beginning of uh list
comprehension the use cases go all over
the place so that's kind of a good
beginner um example to introduce you to
list comprehensions now let's take a
look at a few different ways to do list
comprehensions in a few different use
cases okay so I think a good second
example to show you guys would be
iterating through nested lists also
known as an array more correctly or a
matrix um and to show you how let's say
I have a matrix uh filled with lists and
I want to combine all of the components
in those lists into one list now
typically in Python if you do list
concatenation it will just add those
together um but that's not always going
to be what you actually want and so it's
still several lines of code and in if or
for Loop something like that and there's
a really easy list comprehension for
this so let's say that I have this
Matrix um with a bunch of lists in it
and you know obviously I've done the
alphabet here uh J K L forgot the
alphabet that's embarrassing m j k l m n
o you know we'll leave it there good
enough um let's say that we want to
create a list comprehension to store all
of the values in those different lists
in just one list going forward and to do
that we'll say okay the ABCs are going
to be equal to a character for each list
in The Matrix but that's not really
enough yet because we haven't defined
where character is coming from we want
each character inside of each list in
The Matrix and so what we do is we have
this main Loop and we need to define a
for loop after this main Loop that's
going to run in each iteration of the
loops so what we have to say is four
character in each list so I know that
this is where list comprehensions start
to look really gummy and really kind of
uh goofy if you're not familiar with it
compared to just some nice plain uh for
loops and it's perfectly okay to go back
to what you're comfortable with but I
also think it's very useful to acquaint
yourself with these
examples what we are saying here and the
way to read this is take every character
for each list inside of the
Matrix for each character in that list
so I know the best way to kind of read
this is sort of backwards where we say
take every character in each list for
each list in the matrix it's a little
bit of getting your syntax figured out
but if we run this you'll see and I left
all the code that we were using before
in place so at the end I can just dump
this all in a GitHub for you but what
you can see there is we get one nicely
formatted uh list at the end and you
could do things here like character do
um upper uh if you wanted in all
capitals uh dictionary list or anything
like that so you can still do the stuff
that we figured out in the previous
example of like string transforms or
numerical transforms but this is how you
iterate through lists within a list how
you iterate through matrices and arrays
that have lists inside of lists you
could feel
theoretically have more for conditions
after that or you could have if
conditions after that so that's just
another example showing the power of
list
comprehensions now I want to take a look
at a few examples with numbers this
section of the tutorial will be called
fun with
numbers um no it's not called anything I
don't do things that way okay so let's
say we want to make a quick list and
this is actually a list comprehension
but this isn't really the uh tutorial
let's say we want a quick list of
numbers and this is just going to give
us 0 1 2 3 4 5 6 7 8 and nine this is
basically saying uh 4 I in range 10 uh
you know numbers. append I okay this is
basically just getting us a list of
numbers well let's say I want to make a
list of all of the squares okay I want
to take each number and square it this
is the python Syntax for uh raising to a
power for Num in Num
okay so easy enough if I print squares
then what you'll see uh I spelled it
wrong initially squares then what you'll
see when I run this is I get the numbers
0 through N squared though okay so 0
squared is 0 1 squar 2 3 4 all the way
up to 9 squar pretty cool um obviously
you can do the same thing for cubes if
you wanted I know it's silly to column
squares but now just by changing that
two to a three we've got all these cubed
values and things like that so in a
theoretical world where maybe this isn't
uh 10 numbers maybe this is 100 numbers
and maybe I want to know every cubed
number that is divisible by if num Cub 3
is uh divisible by uh it doesn't matter
six okay so every cubed root that is um
divisible by three but or or divisible
by six with no remainder so to check for
no remainder I want to say modulo 6 is
equal to zero right all right so I know
that was kind of uh just pulled out of a
hat example here but this is going to go
through and Cube every value 0 to 99 and
store it in a list if the cubed value is
divisible by six and I honest to
goodness have no idea which ones those
will be okay um so there you go there
are apparently about 15 of those values
um I I couldn't actually tell you what
these values are uh I guess what we
could do here this is now it's just fun
you know now we're just having fun guys
um okay so here I have added the number
and what its cubed value is if it's
perfectly divisible by six um I don't
know why this is such a surprise to me
but it is all the values that are a
multiple of six which makes perfect
sense right um because all cubing
something is is multiplying it by six
but that was supposed to show you an
example of cubed roots and I can't stop
laughing at myself for uh how silly an
example that is but hopefully you're
still seeing the format of a some value
and some value that can be manipulated
or checked or even turned into a tupal
right like we took a number and we
turned it into a tupal by saying we want
to store both the number and its cubed
value so a for B which is B is the one
that's going to change the least because
it's just the name of your indexing
variable and then in C so whatever list
we're checking through if D some
condition uh to check against or check
for and that is a list comprehension so
I think the last thing I want to do in
this tutorial is talk about kind of the
natural extension of this which is
dictionary comprehensions it's almost
identical to list comprehensions but
there's a couple nuances about uh using
list comprehension style checks against
dictionaries so let's take a look at
just a few quick examples for
those okay so I'm going to run it all
the way back here to kind of our first
list which was just three names only now
I'm going to make it a different uh list
and instead of a list I'm actually going
to make it a
dictionary so assuming you know a little
bit about python a dictionary is
obviously a bunch of keys and then their
values so dictionaries are organized
into key value pairs separated by a
colon and then uh each pair is separated
by a comma so key colon value and then a
comma and then the next key colon the
next value comma stored inside these
curly brackets that's what makes it a
dictionary if I want to transform this
dictionary into a new dictionary let's
say adjusted salary
okay where I want to go through and I
want to take all of the values that were
in that first dictionary and I want to
do something new to them just like the
list
comprehensions the format here is very
similar it's still a for B in C if D
only now you have to know about a couple
little nuances okay so let's say I want
to do two things I want to do a full
uppercase of the name so I want to do
name. uper but then I also want to take
a uh integer value of the salary to the
nearest thousand okay so let's say I
want name. uper and then colon and then
the salary uh I want it to be an integer
and I want to divide it by a th000 okay
so an integer salary divided by a th000
for each name comma salary in salaries
do items okay so and then you need these
parentheses here I'm trying to make sure
my little camera Square doesn't get in
the way of the code um so what this is
saying is take all of the items for each
entry in salaries split it into two
variables called name and then salary
and then uppercase the name and then
take an integer divided by a thousand of
the
salary and then store that in a new
dictionary so if I print adjusted
salaries gosh I hope this works
run okay what you'll see is you've got
all three names fully uppercase so this
is different than tile which we did in
the earlier example up here um and then
you have the integer value of their
salary in thousands okay so it's just a
way of showing you you can transform
both the keys and the values inside of a
dictionary using a dictionary
comprehension at the same time you just
have to know this not tricky necessarily
but slightly new syntax until you get
used to dictionary and list
comprehensions um just like before you
could say if salary greater than uh
100,000 if you wanted to or if int of
salary divided by a
th000 is greater than 100 it's basically
the same check just written in a
different way um so this should only
give us people whose salaries are above
100K and it does um Pete drops off of
there and then you could add another
thing that we haven't talked about yet
in list comprehensions and in dictionary
comprehensions you can combine if
statements uh and you can do this two
different ways so you can say if the
salary is over a th000 and if name dot
starts with p okay and so if you've been
paying attention to our list you know
this will probably only return Phillip
all right um and you can do that by
saying if and then another if or you can
do it this way you can say if and then
you can uh just like any other time you
can put two conditionals inside of
uh inside of parentheses and use the
keyword and okay so uh this is a
dictionary comprehension this is also
shown that you can combine if
conditional statements this is true for
dictionaries and lists um and I think
all of the examples combined in this
video so far I will drop this code if
you want exactly these examples um in a
GitHub and I'll leave a link to it in
the description of this video but you
can probably cook up these examples or
similar examples very quickly and easily
yourself um there are so many use cases
for list comprehensions and dictionary
comprehension I'm sure there are
probably things that I glossed over
things that possibly we missed um but I
hope all in all this video was useful
and taught you what you were looking for
um if you have any questions be sure to
let me know about in the comments below
it was really nice to be able to just
put together a Python tutorial which is
kind of how this channel got start I've
been diving into a lot of hardware and
going all over the place lately so it's
nice to get back to the roots a little
and do hopefully a useful Python
tutorial for everybody be sure let me
know in the comments below what you'd
like to see more of on the channel uh
don't forget to leave a like on the
video subscribe to the channel if you've
been enjoying the content consider
checking out my patreon there's a link
below in the video as well and as always
a massive thank you to my patreon
supporters as well as everyone leaving
likes and watching on L Master Tech
YouTube good luck with your projects
until next time bye
