How to Use List Comprehension in Python
Python List Comprehension
Have you ever come across a bunch of data where you need to filter out some elements or perform certain operations on each item? You might even want to create a whole new list based on the original one. If yes, then you might have wondered if there is a single term that will make it possible to do all of this. Well, we will be learning about just that- Python List Comprehension!
In this Python Tutorial, we will try to understand Python List Comprehension and various uses of List Comprehension in Python. If you are new to Python Programming, you should first go through all the basic concepts. Python Certification Training would be the best place to get you started with Python Development.
Read More: Top 50 Python Interview Questions and Answers |
What is Python List Comprehension?
List Comprehension in Python is a way through which we can write concise, readable codes while we are creating lists in our Python program. Traditionally, you might be using loops and conditionals and even writing several lines of code to achieve the same result. It's time for you to stop and get the easy way with list comprehension that will let you do it all in just one line. Sounds simple right?
Let's look at the basic structure of using list comprehension in a Python program.
Syntax of List Comprehension in Python
new_list = [expression for item in original_list if condition]
- expression- this will hold what has to be done with each item in the original list.
- item- this is the variable that holds each element in the original list.
- original_list-this is the list you are iterating over.
- condition- it is an optional condition that will help filter elements.
Example of List Comprehension in Python
# Original list
numbers = [1, 2, 3, 4, 5]
# List comprehension to double each number
doubled_numbers = [num * 2 for num in numbers]
print(doubled_numbers)
Output
[2, 4, 6, 8, 10]
for Loop vs. List Comprehension
Aspect | for Loop | List Comprehension |
Performance | The 'for' loop is slightly low in terms of performance. | List comprehension has optimized implementation which results in better performance in many cases. |
Code Length | It requires more lines. | It is more concise as compared to for loop. |
Readability | the code has comparatively less readability. | It has more concise and readable code. |
Scope | It defines the empty list beforehand and then modifies it within the loop. | It creates a new list in a single expression which is scoped to the comprehension itself. |
Suppose, we have a list of numbers and we want to create a new list that will display only the even numbers. We will try to use both for loop and list comprehension to understand the difference.
Example using Traditional 'for' Loop:
# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Empty list to store even numbers
even_numbers = []
# Loop to filter even numbers
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers)
Output
[2, 4, 6, 8, 10]
Example using List Comprehension:
# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# List comprehension to filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
Output
[2, 4, 6, 8, 10]
As you can see, we got the same output in both cases but using list comprehension, we did it in a slightly shorter time, that too, in a single line of code.Read More: Python Developer Salary |
Using Conditions in List Comprehension
# Original list
words = ["apple", "banana", "orange", "kiwi", "pear", "strawberry"]
# List comprehension to filter words with more than 5 characters
long_words = [word for word in words if len(word) > 5]
print(long_words)
Output
['banana', 'orange', 'strawberry']
Now try adding an else statement that will specify a default value for elements that don't meet the condition.
# Original list
numbers = [1, 2, 3, 4, 5]
# List comprehension to label even and odd numbers
even_or_odd = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]
print(even_or_odd)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']
Nested List Comprehensions
# Nested list of numbers
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Nested list comprehension to transpose the matrix
transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed_matrix)
Output
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Advantages of List Comprehension
- It allows us to write concisely within a single line of code.
- It makes the code easier to read and understand.
- It is rather less complex than the traditional for loops as they don't have temporary variables and separate loop constructs.
- In many cases, list comprehensions can be seen as having higher performance as compared to traditional loops.
- They support a wide range of operations like filtering, mapping, and nesting.
Conclusion
FAQs
Q1. What is a list comprehension in Python?
Q2. What are the 4 types of comprehension in Python?
- List Comprehension
- Dictionary Comprehension
- Set Comprehension
- Generator Comprehension
Q3. Is Python list comprehension faster?
Q4. What are the 2 main types of comprehension?
- List Comprehension
- Dictionary Comprehension