15 Python List Comprehension Examples You Need to Know

Python List Comprehension

Python is one of the most widely used programming languages today. One of its strengths is the ease of working with lists, which are collections of items. Python list comprehensions are a concise way to create lists from other lists, providing a powerful tool for data manipulation and analysis. In this article, we will explore 15 examples to help you master Python list comprehensions.

Introduction to Python List Comprehensions

Before diving into examples, let’s define what a list comprehension is. A list comprehension is a concise way to create a new list by applying an expression to each item in an existing list. It consists of three parts: the input sequence, the variable representing each item in the input sequence, and the expression to apply to each item.

List comprehensions are often more concise than traditional for loops and map/filter functions, and can be easier to read and understand.

Example 1: Squaring Numbers

Suppose we have a list of numbers and want to create a new list with the squares of each number. Here’s how we can use a list comprehension to achieve this:

numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]

The x ** 2 expression is applied to each item in the numbers list, and the resulting values are stored in the squares list.

Example 2: Filtering Even Numbers

Sometimes we only want to include certain items from the input list in the output list. For example, we might want to create a new list with only the even numbers from an existing list. Here’s how we can use a list comprehension to achieve this:

numbers = [1, 2, 3, 4, 5]
evens = [x for x in numbers if x % 2 == 0]
print(evens) # Output: [2, 4]

The if x % 2 == 0 condition filters out any odd numbers from the numbers list, leaving only the even numbers in the evens list.

Example 3: Creating Tuples

List comprehensions can also be used to create tuples, which are similar to lists but are immutable (i.e., cannot be changed after creation). Here’s an example of creating a list of tuples using a list comprehension:

names = ['Alice', 'Bob', 'Charlie']
pairs = [(name, len(name)) for name in names]
print(pairs) # Output: [('Alice', 5), ('Bob', 3), ('Charlie', 7)]

The expression (name, len(name)) creates a tuple with the name and its length, and this tuple is created for each name in the names list.

Example 4: Nested Lists

List comprehensions can also be nested, allowing us to create more complex data structures. Here’s an example of creating a nested list using a list comprehension:

rows = 3
cols = 3
matrix = [[i + j for j in range(cols)] for i in range(rows)]
print(matrix) # Output: [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

The inner list comprehension [i + j for j in range(cols)] creates a list of values for each row in the matrix, and the outer list comprehension [...] for i in range(rows)] creates a new list for each row.

Example 5: Flattening Nested Lists

We can also use list comprehensions to flatten nested lists, which means converting a list of lists into a single list. Here’s an example:

nested = [[1, 2], [3, 4], [5, 6]]
flat = [x for sublist in nested for x in sublist]
print(flat) # Output: [1, 2, 3, 4, 5, 6]

The inner loop for x in sublist iterates over each element in each sublist, and the outer loop for sublist in nested iterates over each sublist in the nested list.

Example 6: Removing Duplicates

We can use list comprehensions to remove duplicates from a list, by creating a new list with only the unique elements. Here’s an example:

numbers = [1, 2, 3, 2, 1, 4, 5]
unique = list(set(numbers))
print(unique) # Output: [1, 2, 3, 4, 5]

The set(numbers) expression creates a set, which by definition only contains unique elements. We then convert the set back to a list using the list() function.

Example 7: Finding Common Elements

We can use list comprehensions to find the common elements between two lists. Here’s an example:

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common = [x for x in list1 if x in list2]
print(common) # Output: [3, 4]

The if x in list2 condition filters out any elements in list1 that are not also in list2, leaving only the common elements in the common list.

Example 8: Using Conditionals

List comprehensions can also use more complex conditionals, allowing us to create more specific lists. Here’s an example:

words = ['hello', 'world', 'python', 'is', 'awesome']
long_words = [word for word in words if len(word) > 5]
print(long_words) # Output: ['python', 'awesome']

The len(word) > 5 condition filters out any words that are not longer than 5 characters, leaving only the longer words in the long_words list.

Example 9: Combining Lists

We can use list comprehensions to combine two or more lists into a single list. Here’s an example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = [x + y for x in list1 for y in list2]
print(combined) # Output: [5, 6, 7, 6, 7, 8, 7, 8, 9]

The inner loop for y in list2 iterates over each element in list2, and the outer loop for x in list1 iterates over each element in list1. The expression x + y creates a new element for each combination of elements from list1 and list2.

Example 10: Multiple Conditions

We can use multiple conditions in a list comprehension, allowing us to create even more specific lists. Here’s an example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered

filtered = [x for x in numbers if x % 2 == 0 if x > 4] print(filtered) # Output: [6, 8, 10]


The two conditions `if x % 2 == 0` and `if x > 4` are combined using the `and` operator, so only elements that satisfy both conditions are included in the `filtered` list.

## Example 11: Creating Tuples

List comprehensions can also be used to create tuples. Here's an example:

```python
numbers = [1, 2, 3, 4, 5]
tuples = [(x, x**2) for x in numbers]
print(tuples) # Output: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

The expression (x, x**2) creates a tuple for each element in the numbers list.

Example 12: Creating Dictionaries

List comprehensions can also be used to create dictionaries. Here’s an example:

words = ['hello', 'world', 'python', 'is', 'awesome']
dictionary = {word: len(word) for word in words}
print(dictionary) # Output: {'hello': 5, 'world': 5, 'python': 6, 'is': 2, 'awesome': 7}

The expression word: len(word) creates a key-value pair for each element in the words list, where the key is the word itself and the value is the length of the word.

Example 13: Reversing a List

We can use list comprehensions to reverse a list. Here’s an example:

numbers = [1, 2, 3, 4, 5]
reversed_list = [numbers[len(numbers) - 1 - i] for i in range(len(numbers))]
print(reversed_list) # Output: [5, 4, 3, 2, 1]

The expression numbers[len(numbers) - 1 - i] accesses each element of the numbers list in reverse order, using the loop variable i to calculate the index of each element.

Example 14: Splitting a String

We can use list comprehensions to split a string into a list of words. Here’s an example:

sentence = 'Python is a high-level programming language.'
words = sentence.split()
print(words) # Output: ['Python', 'is', 'a', 'high-level', 'programming', 'language.']

The split() method splits the string at whitespace characters (spaces, tabs, and newlines) and returns a list of words.

Example 15: Joining a List

We can use list comprehensions to join a list of words into a single string. Here’s an example:

words = ['Python', 'is', 'a', 'high-level', 'programming', 'language.']
sentence = ' '.join(words)
print(sentence) # Output: 'Python is a high-level programming language.'

The join() method joins the elements of the words list into a single string, using a space character as the separator.

Conclusion

Python list comprehensions are a powerful and concise way to create new lists based on existing ones. They allow us to perform a wide range of operations, from simple filtering and mapping to more complex transformations and combinations. By mastering list comprehensions, we can write cleaner, more efficient, and more expressive code, and take our Python programming skills to the next level.