Facebook Pixel

List Comprehension

List comprehensions are used to create new lists from existing iterables such as lists, tuples, dictionaries, sets, arrays, or even strings.

Syntax:

example_list = [expression(item) for item in iterable if condition]
  • expression: the value to put into the new list.
  • iterable: a sequence or collection you can loop over (lists, tuples, dictionaries, sets, strings, etc.)
  • condition: condition checks if the item should be added to the new list or not.

Example 1: accepts items with the small letter “o” in the new list

names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if "o" in item]
print(namesWith_O)

This comprehension checks each name and includes it only if it contains the letter "o".

Output:

['Milo', 'Bruno', 'Rosa']

Example 2: accepts items which have more than 4 letters

names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesLong = [item for item in names if len(item) > 4]
print(namesLong)

Output:

['Sarah', 'Bruno', 'Anastasia']