Predictive Hacks

Python list comprehension cheat sheet

Python List Comprehension

Python’s list comprehension is a very useful asset for a programmer and a reason for us to love Python. It’s a special syntax, creating lists out of lists and transforming many lines of code into a single one. Let’s dive into it.

Basic List Comprehension


#It creates the same list as l1

[i for i in l1]

['a', 'b', 'c', 'd', 'e', 'f']

If Statement


#If statement. Filter the list if the element is "a" 

[i for i in l1 if i!="a"]

['b', 'c', 'd', 'e', 'f']

Transform the elements of a list


#It makes uppercase the letters

[i.upper() for i in l1]

['A', 'B', 'C', 'D', 'E', 'F']

If Else Statement


#It makes uppercase the letters except "a"

[i.upper() if i!="a" else i for i in l1]

['a', 'B', 'C', 'D', 'E', 'F']

Advanced List Comprehension

Use elements of 2 lists


#It combines the elements of the l1 and l2
[i+str(j) for i in l1 for j in l2]

['a1', 'a2', 'b1', 'b2']

Example: Get the email addresses from a list of domains

l1=["[email protected]", "[email protected]","","", "[email protected]"]

#It searches for email addresses with domains that are in the list "domains"
[i for i in l1 for j in domains if j in str(i)]

['[email protected]', '[email protected]']

Create a list of tuples


#It creates list of tuples containing
#the elements of the list with their number of characters

[(i,len(i)) for i in l1 ]

[('billy', 5), ('mike', 4), ('george', 6), ('italy', 5), ('greece', 6)]

Interact with other elements of the list


#It creates a list with items the numbers that are before 0 in l2
[l1[i-1] for i,j in enumerate(l1) if j==0]

[6, 9, 5]

Dict Comprehension

As with List Comprehension, you can apply the same rules to dictionaries but you have to use curly brackets and set the key and value pairs. We will show you some examples.

Create a dictionary from a list


#It creates a dictionary

{i:i for i in l1}

{'a': 'a', 'b': 'b', 'c': 'c', 'd': 'd', 'e': 'e', 'f': 'f'}

#It creates a dictionary enumerating every item of the list

{i:j for i,j in enumerate(l1)}

{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

Iterate over keys & values of a dictionary

d1={0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

#It creates a dictionary adding 1  to the keys of d1
{key+1:value for key , value in d1.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

data science journey

My Journey as a Data Science Blogger

Μy Background My Studies Back in 2001, I entered university to study Statistics. During my first year, I ran my