List Comprehension
List comprehension is an elegant way to define and create lists based on existing lists in Python. It can be used to create a new list from an existing one by specifying instructions on how to transform its elements, and also allows you to filter out items from the original list.
Syntax
The typical syntax for list comprehension in Python is as follows:
Here is what each segment represents:
expression
: Transforms the item before it is added to the new list.iterable
: Any object you can iterate over.condition
(Optional): An optional condition that must be met for an item to be included in the new list.
Example
Let’s look at an example where we want to create a new list of squares for all numbers in an existing list.
Output:
Here, the expression
is number**2
, the iterable
is numbers
and there is no condition
.
We can also apply a condition
to filter items from the original list. For instance, we can create a list of squares for only the even numbers in our original list:
Output:
Here, the condition
is number % 2 == 0
, which verifies if a number is even.
Note
You can also use list comprehension with other iterables such as strings, tuples, and dictionaries.