Python Python Loop Through List Items
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Example: You want to create a list of all the fruits that has the letter "a" in the name.
Without list comprehension you will have to write a for
statement
with a conditional test inside:
Example
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
newlist = [x for x in fruits if "a" in x]
print(newlist)
The list comprehension is wrapped around square backets, contains one or more for
statements, zero or more if
statements, and returns a new list.
Related Pages
Python Lists Tutorial Lists Access List Items Change List Item Loop List Items Check If List Item Exists List Length Add List Items Remove List Items Copy a List Join Two Lists