Python - For loop in square brackets

By xngo on June 28, 2019

In Python source code, you sometimes see a for loop inside a square bracket, []. It is called List comprehension. It is a way to create a new list from an old list. It has the following syntax.

new_list = [ NEW_VALUE for item in YOUR_LIST ]

You should read it as: For each item in YOUR_LIST, assign the new value to NEW_VALUE.

To make it more clear, here is an example that adds 1 to every single integer of the list.

my_list = [ 2, 5, 6 ]
new_list = [ item+1 for item in my_list ]
print(new_list)

Output

[3, 6, 7]

Here is another example. The list comprehension will to create a new capitalized list of words.

fruits = [ 'banana', 'pineapple', 'guava' ]
 
capitalize_fruits = [ f.capitalize() for f in fruits ]
 
print(capitalize_fruits)

Output

['Banana', 'Pineapple', 'Guava']

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.