Python’s list comprehension is a powerful and concise way to create lists. Providing compact syntax for creating lists in a single line of code, it makes your code more readable and efficient.
Codemagnet has come up with an article, which will help you explore the basics of list comprehension and dive into live examples to help you master this essential Python feature.
What is List Comprehension?
List comprehension is a concise way to create lists in Python. It allows you to create a new list by applying an expression to each item in an existing list (or another iterable). The syntax for list comprehension is [expression for item in iterable if condition], where expression is the output expression, item is the variable representing each item in the iterable, and condition is an optional filter that only includes items for which the condition is true.
Basic List Comprehension Examples:
Lets take some examples and try to understand list comprehension in depth
Creating a list of squares of numbers from 1 to 5:
squares = [x**2 for x in range(1, 6)]
print(squares)

Explanation:
for x in range(1, 6): This part iterates over numbers from 1 to 5 (range(1, 6)generates numbers from 1 to 5, excluding 6) and assigns each number to the variablex.x**2: This is the expression part of the list comprehension. It calculates the square ofxfor each iteration.[x**2 for x in range(1, 6)]: This is the list comprehension syntax, which combines the iteration and expression parts to create a new list containing the squares of numbers from 1 to 5.squares = [x**2 for x in range(1, 6)]: This assigns the list created by list comprehension to the variablesquares.print(squares): This prints the list of squares[1, 4, 9, 16, 25].
Why is this way efficient to write the code?
Using list comprehension in this way is more efficient and concise compared to traditional approaches using loops because:
- Readability: List comprehension makes the code more readable and expressive. It clearly conveys the intent of creating a list of squares in a single line of code.
- Compactness: It reduces the amount of code needed to achieve the same result. In this case, it replaces multiple lines of code that would be required for a loop-based approach.
- Performance: List comprehension is generally faster than traditional loops in Python because it is optimized for speed. It leverages the underlying Python interpreter’s optimization techniques to perform the operation efficiently.
Filtering even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)

Creating a list of tuples:
fruits = ['apple', 'banana', 'cherry']
fruit_tuples = [(fruit, len(fruit)) for fruit in fruits]
print(fruit_tuples)

Explanation:
fruits = ['apple', 'banana', 'cherry']: This line creates a list calledfruitscontaining three strings:'apple','banana', and'cherry'.fruit_tuples = [(fruit, len(fruit)) for fruit in fruits]: This line uses a list comprehension to create a list of tuples calledfruit_tuples. The list comprehension iterates over each element in thefruitslist (for fruit in fruits) and creates a tuple(fruit, len(fruit))for eachfruit, wherelen(fruit)is the length of thefruitstring. So, for eachfruitin thefruitslist, a tuple is created containing thefruititself and its length.(fruit, len(fruit)): This is the expression part of the list comprehension. It creates a tuple with two elements:- The first element is the
fruititself, which is the current element in the iteration. - The second element is the length of the
fruitstring, calculated using thelen()function.
- The first element is the
print(fruit_tuples): This line prints thefruit_tupleslist, which contains tuples of fruits and their lengths. The output will be:['apple', 5), ('banana', 6), ('cherry', 6)].
let’s look at some more advanced examples to demonstrate the flexibility and power of list comprehension:
Advanced List Comprehension Examples:
Flattening a nested list:
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened_list = [x for sublist in nested_list for x in sublist]
print(flattened_list)

Explanation:
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]: This line creates a nested list callednested_listcontaining three sublists:[1, 2, 3],[4, 5], and[6, 7, 8].flattened_list = [x for sublist in nested_list for x in sublist]: This line uses nested list comprehension to flatten thenested_listinto a single list calledflattened_list. The expression[x for sublist in nested_list for x in sublist]iterates over each sublist innested_listand then iterates over each elementxin the sublist. This effectively flattens the nested list structure into a single list.for sublist in nested_list: This is the outer loop that iterates over each sublist innested_list.for x in sublist: This is the inner loop that iterates over each elementxin the current sublist.
print(flattened_list): This line prints theflattened_list, which is the flattened version of thenested_list. The output will be[1, 2, 3, 4, 5, 6, 7, 8].
Using conditional expressions:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
number_types = ['even' if x % 2 == 0 else 'odd' for x in numbers]
print(number_types)

Creating a dictionary from two lists:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = {k: v for k, v in zip(keys, values)}
print(dictionary)

Transposing a Matrix:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Using Enumerate with List Comprehension:
words = ['apple', 'banana', 'cherry']
indexed_words = [(i, word) for i, word in enumerate(words)]
print(indexed_words) # Output: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
Expalantion:
words = ['apple', 'banana', 'cherry']: This line creates a list namedwordscontaining three strings: ‘apple’, ‘banana’, and ‘cherry’.indexed_words = [(i, word) for i, word in enumerate(words)]: This line uses a list comprehension to create a new list namedindexed_words. It iterates over each element in thewordslist using theenumerate()function, which returns a tuple containing the index (i) and the value (word) of each element. For each element, it creates a tuple(i, word)and adds it to theindexed_wordslist.enumerate(words)returns an iterable that yields pairs of indices and values from thewordslist.for i, word in enumerate(words)iterates over each pair, unpacking it into the variablesi(index) andword(value).(i, word)creates a tuple containing the indexiand the wordword.
print(indexed_words): This line prints theindexed_wordslist to the console.- Output:
[(0, 'apple'), (1, 'banana'), (2, 'cherry')]: This is the output of theprint()statement, showing the index-value pairs for each word in thewordslist. Each tuple represents the index and the corresponding word from thewordslist.
Using Nested List Comprehension for Matrix Multiplication:
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
product = [[sum(a*b for a, b in zip(row1, col2)) for col2 in zip(*matrix2)] for row1 in matrix1]
print(product) # Output: [[19, 22], [43, 50]]
Conclusion:
List comprehension is a powerful feature in Python that allows you to create lists in a concise and readable way. By mastering list comprehension, you can write more efficient and expressive code. We’ve covered the basics of list comprehension and explored various examples to help you understand its usage. Experiment with different examples and use cases to enhance your Python programming skills.





Leave a Reply