PythonSyntax and keywords
List comprehensions
A concise way to build lists, sets, and dictionaries from other collections.
Example
#Python
scores = [45, 82, 67, 91, 30]
passed = [s for s in scores if s >= 60]
curved = [min(s + 10, 100) for s in scores]
print(passed)
print(curved)Resultsaved result, you can check it
[82, 67, 91]
[55, 92, 77, 100, 40]
Definition and usage
#A list comprehension builds a new list in a single line: [x * 2 for x in numbers]. It combines a loop with a transformation, and an optional if condition at the end filters the items.
The same syntax works for sets ({β¦}), dictionaries ({k: v for β¦}), and generators ((β¦)). A generator does not build the whole list right away, it supplies items on demand instead, which saves memory.
List comprehensions are readable as long as they stay short. Nested loops and several conditions in one expression are better written out as an ordinary for loop.
Syntax
#Syntax
[expression for element in collection if condition]More examples
#Python
names = ["Emma", "Jack", "Mia", "Emma"]
lengths = {name: len(name) for name in names}
unique = {name.lower() for name in names}
total = sum(len(name) for name in names)
print(lengths)
print(sorted(unique))
print(total)Resultsaved result, you can check it
{'Emma': 4, 'Jack': 4, 'Mia': 3}
['emma', 'jack', 'mia']
15
Good practices
#- For sums and checks (
sum,any,all), pass a generator expression without square brackets. It does not create an unnecessary list. - If the expression does not fit on one readable line, write it out as a loop instead.
Related entries
#- map() vs list comprehensionmap() calls a function for every element and returns a lazy iterator, while a list comprehension builds a new list right away and can filter with an if condition.
- forA loop that goes through the successive items of a sequence or other iterable object.
- Dict comprehensionsA concise way to build a new dictionary by transforming or filtering another collection.
- map()Calls a function for every item and returns an iterator of results.
- filter()Returns an iterator of items for which a function returns a truthy value.
Spotted a mistake or missing an example? Write to us.