Introduction
Python uses an elegant method called list comprehension to work with lists. The method enables programmers to work with lists (an array-like Python data type) in a readable and single-line format.
List comprehensions are a must-know syntax construct, whether you're just learning Python or a well-versed developer.
This guide explains Python list comprehension through hands-on examples.
Prerequisites
- Python 3 installed.
- An IDE or code editor to write and run code examples.
Python List Comprehension Syntax
List comprehension generates new lists by applying an expression to items extracted from another iterable (such as a list, range, or tuple). In Python, the syntax looks like the following:
list = [expression for element in iterable if condition]
The syntax consists of the following parts:
expression
is a calculation performed on an element. The element resulting from the expression appends to the newly created list.element
is an item extracted from an iterable on which the expression applies.iterable
is an iterable from which the elements are extracted.condition
is an optional check whether the element meets the provided condition.
The list comprehension syntax stems from set builder notation in mathematics.
List Comprehension vs. Other Methods
List comprehensions serve as a replacement for other list-creation methods in Python. The sections below demonstrate how these methods compare to the other methods and how to rewrite the same expression with list comprehension.
List Comprehension vs. for Loop in Python
Both list comprehensions and for
loops iterate over a list, range, or tuple. They allow performing operations on extracted items.
For example, the following code uses a for
loop to generate a list of squares between zero and four:
squares = []
for number in range(0, 5):
squares.append(number**2)
print(squares)
The following code does the same using list comprehension:
squares = [number**2 for number in range(0, 5)]
print(squares)
In both instances, the code generates a list of squared numbers.
List Comprehensions vs. Lambda Functions
Both list comprehensions and lambda functions filter values when generating a new list from an existing one.
For example, to generate a list of even values between zero and five using lambda functions:
numbers = [0, 1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
The filter()
function helps filter values from the list based on the condition defined in the lambda function.
The same output can be generated using list comprehension:
numbers = [0, 1, 2, 3, 4, 5]
even = [number for number in numbers if number % 2 == 0]
print(even)
However, there is a critical difference between the two approaches apart from the syntax. Lambda functions are a shorthand way to write a Python function without a name. They have a broader application than list comprehensions, as they can output values other than lists.
Benefits of Using List Comprehensions
List comprehension is often preferable in Python compared to loops and other methods. The main benefits of using list comprehensions are:
- Convenience. List comprehensions are very convenient to use for simple list operations. Compared to other methods, the code is shorter and easy to read.
- Readability. Due to its compactness, list comprehensions are generally readable and shorter than alternative list methods.
- Reduced redundancy. List comprehensions reduce boilerplate code. The syntax avoids defining an empty list and then populating the list with elements one by one based on some condition.
- Immutability. The new list does not affect or change the original list or its values.
Python List Comprehension Examples
List comprehension simplifies working with iterable objects in various use cases and examples. Below are some typical examples to create, filter, and change lists using this method.
Creating a List of Squares
Use list comprehension to create a list of squares. The range()
function generates a number range for this task. For example:
squares_list = [number**2 for number in range(0, 10)]
print(squares_list)
The resulting list contains squared numbers between zero and ten.
Filtering a List
Add a condition to filter a generated or existing list. For example:
odd = [number for number in range(0, 10) if number % 2 != 0]
print(odd)
The list contains odd numbers between zero and ten.
Formatted Strings List
List comprehension can be used to format a list of strings quickly. For example:
words = ["These", "Words", "Are", "Capitalized"]
lowercase = [word.lower() for word in words]
print(lowercase)
The resulting list contains the same words in lowercase format.
Filtering words
List comprehension lets you filter a list containing words based on a condition. The following code shows how to filter words based on the number of letters a word has:
words = ["Filtering", "words", "based", "on", "length"]
five = [word for word in words if len(word) >= 5]
print(five)
The generated list contains only words with at least five letters.
Nested List Comprehension
List comprehension enables looping through multi-dimensional lists and flattening them into a single-dimensional output list. For example, to extract all elements from a nested list, use the following example:
nested = [[1, 2], [3, 4], [5, 6]]
elements = [element for pair in nested for element in pair]
print(elements)
The syntax uses two for
loops to move down the lists and extract each element. The newly formed list contains all individual elements in a single dimension.
Generating Pairs
Use list comprehension on two lists to generate all pair combinations between two lists. For example:
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
pairs = [(x, y) for x in list1 for y in list2]
print(pairs)
The resulting list contains a list of tuples that have all combinations between the two initial lists.
When Not to Use List Comprehension?
List comprehension is only suitable in some situations. Avoid using it in situations where there are:
- Complex expressions or conditionals. When the logic to filter or transform elements is complex, the code syntax becomes hard to read. In these cases, resort to using regular
for
loops and aim for readability. - Several linked operations on elements. Situations requiring multiple operations or operations that modify external elements are unsuitable for list comprehensions.
- Multiple nested lists. Working with multiple nested lists becomes unreadable with list comprehensions, resulting in harder-to-maintain code.
- Memory concerns. Since it creates a new list, the method is unsuitable for memory-intensive tasks and large lists.
When these situations appear, use a different method to generate or filter a list. Some options include generator functions and for
loops.
Conclusion
After reading this guide, you learned what list comprehension in Python is and how to use it in your code effectively.
Next, learn how to substring a string in Python using methods such as string slicing.