Skip to main content

Python quick bite 03 - List Comprehension

 Here is another quick bite on a python concept. Looks like I am enjoying this short post too much. Ops. Gonna prepare a longer post next.

To iterate through a list and adding the item to a list will look something like this. In this example, I will iterate a word and change it to a list. 

#1. You need an empty list.

empty_list = []

#2. You need the word you to iterate and a for loop.

word = "Comprehension"

for letter in word: # the letter is just for you to iterate (you can iterate through a string/list)

#if you print the empty_list, you will get this output


With the use of list comprehension, the whole code is greatly shortened.

The syntax looks something like this:

new_list = [ expression for item in iterable_item]

This works by first looping through the item in iterable_item like list/string/dictionary keys.

Then the expression, what to add to the new list. 

The 4 lines of code now will look like this:

eg 1. empty_list = [letter for letter in word] 

So we will add a letter to the empty_list for every letter in the word.

number_list = [1,3,5]

eg 2. new_number_list = [no+2 for no in number_list]

output for eg 2, for each no in the number_list, it is added by 2.


List comprehension becomes more powerful with the use if condition. 

new_list = [ expression for item in iterable_item if condition == True ]

eg 3. animal_names = ['elephant', 'giraffe', 'horse', 'cat']

animal = [animal.upper() for animal in animal_names if len(animal) > 3]

output for eg 3. for each name in the animal_names list, only the names that have more than 3 characters are selected and I had formatted the string to uppercase. 


So there you have it! This simplifies your code and makes it shorter. 

List comprehension for dictionary.

I find this to be tougher to understand >< 

new_dict = {new_key:new_value for item in list} 

new_dict = {new_key:new_value for (key,value) in dict.items()}

new_dict = {new_key:new_value for (key,value) in dict.items() if test}

eg 4. names = ['Alex','Beth','Caroline','Dave']

import random

pocket_money = {student:random.randint(1,100) for student in names} # I randomly generated a dictionary for amount of money and thus you will have a different result as mine. 


{'Alex': 26, 'Beth': 86, 'Caroline': 51, 'Dave': 31}

rich_students = {student:money for (student, money) in pocket_money.items() if money > 60}

I am creating a dictionary called rich_students with the student as key and money is value for (each value pair) in pocket_money dictionary where money is > 60. 


{'Beth': 86}

To loop through rows of a dataframe
for (index, row) in df.iterrows():
print(row) #this will give you the content of each row as a pandas series object but because it is a series object, you can call upon the row attributes using row['heading'] to call on the values in that column.