Python List Comprehensions

Python List Comprehensions

Python list comprehensions can be tough to get your head around. They look like for loops inside of lists. In fact, that’s what they are! They can be very useful if you’re trying to write short code. Here is the basic syntax:

<variable name> = [<expression> for <item> in <iterable> if <condition> == True]

(An iterable is something you can use in a for loop, like lists, tuples or the output of the range() function.

An example:

computer_ages = {"eniac": 1945, "imac": 1998, "iphone": 2007, "nexus", 2010, "chromebook": 2010}
# Selects all the computers with an age 2000 or greater.
new_computers = [computer for computer in computer_ages.keys() if computer_ages[computer] > 1999]
print(new_computers)
# Prints ['iphone', 'nexus', 'chromebook']

This list comprehension loops through the dictionary of computers and their respective ages and adds all of the computers made later than 1999 to a list called new_computers.

Here is another example, from W3Schools:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

# Selects all the fruits with an "a" in them
a_fruits = [x for x in fruits if "a" in x]

print(a_fruits)
# Prints ['apple', 'banana', 'mango']

This one loops through a list of fruits and adds all of the fruits with an “a” in their names to a list called a_fruits.

One thought on “Python List Comprehensions

  • Comments are closed.