Member-only story
List comprehensions are an elegant way to create lists in Python by condensing multiple lines of code into one line. They consist of brackets containing expressions, optional conditionals, and loops, making it possible to generate complex lists effortlessly. This guide will walk you through the basic syntax of list comprehensions using current Python features. Let’s dive right in!
The Simplest Form
At their core, list comprehensions have three components: input sequence(s), output expression, and an optional for
loop. Here is the simplest form:
# Creating a new list from numbers 0 to 9
numbers = [x for x in range(10)]
print(numbers) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In this example, range(10)
is the input sequence, while x for x in ...
represents the output expression. For each element x
in the input sequence, the output expression generates a value which gets added to the resulting list.
Adding Conditions
You can add conditions to filter elements within the input sequence like so:
# Only even numbers between 0 and 9…