List comprehensions in Python are a concise and efficient way to create a new list based on existing iterable (e.g. list, tuple, dictionary, set) objects. Here's a beginner-friendly tutorial:
Basic syntax
Python
[expression for item in iterable]
expression:
what to do with each item in the iterableitem:
a variable representing each item in the iterableiterable:
a list, tuple, dictionary, set, etc. that you want to create the new list from.
Example:
Create a new list of squares of numbers from 0 to 4:
Python
numbers = [0, 1, 2, 3, 4]
new_list= [x**2 for x in numbers]
print(new_list)
# Output
[0, 1, 4, 9, 16]
With conditional (if clause):
condition:
a statement to be evaluated for each item in the iterable
Python
[expression for item in iterable if condition]
Example:
Create a new list of even numbers from 0 to 4:
Python
numbers = [0, 1, 2, 3, 4]
even_list = [x for x in numbers if x % 2 == 0]
print(even_list)
# Output
[0, 2, 4]
Nested List Comprehension
Python
[expression for outer_item in outer_iterable for inner_item in inner_iterable]
outer_item:
a variable representing each item in the outer_iterableouter_iterable:
an outer list, tuple, dictionary, set, etc.inner_item:
a variable representing each item in the inner_iterableinner_iterable:
an inner list, tuple, dictionary, set, etc.
Example:
Create a new list of all possible combinations of two letters from two lists:
Python
letters_1 = ['a', 'b', 'c']
letters_2 = ['x', 'y', 'z']
combined_list = [(x, y) for x in letters_1 for y in letters_2]
print(combined_list)
# Output
[('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'x'), ('b', 'y'), ('b', 'z'), ('c', 'x'), ('c', 'y'), ('c', 'z')]
Note: List comprehensions can be useful for processing data in an efficient way, but can become hard to read for complex expressions. It's recommended to use for-loops when you need to perform more complex operations.