Concept: Comprehension
Comprehensions are a concise way to create new collections (lists, sets[1], or dictionaries) by applying an expression to each item in an existing collection. They allow you to generate a new collection in a single line of code, making your code more readable and concise.
# Create a new list of squares from an existing list of numbers
numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
# Create a new list of the squares of even numbers from an existing list of numbers
even_squares = [x ** 2 for x in numbers if x % 2 == 0]
# Create a new dictionary of squares from an existing list of numbers
squares_dict = {x: x ** 2 for x in numbers}Comprehensions exist for lists and dictionaries, but not for tuples. It is, however, possible to create a tuple using comprehension syntax, but the result will be a generator object, which can be converted to a tuple using the tuple() function.
# Create a new tuple of squares from an existing list of numbers
numbers = [1, 2, 3, 4, 5]
squares_gen = (x ** 2 for x in numbers) # This creates a generator object
squares_tuple = tuple(squares_gen) # Convert the generator to a tuple
# Combine the creation of the generator and the conversion to a tuple in one line
squares_tuple = tuple(x ** 2 for x in numbers)We do not cover sets in this course, they are a collection type that is similar to lists and dictionaries. Where they differ is that they are unordered and do not allow duplicate values. You can read more about sets in the official Python documentation. ↩︎