10 Examples you should Try to Master List Comprehensions in Python
This article was published as a part of the Data Science Blogathon
In this article, we’ll study Python list comprehensions, and the way to use them. The topics which we’ll be discussing in this article are as follows:
- What’s the difference between List Comprehension and For loop in Python?
- Syntax of List Comprehensions in python
- Difference between Lambda functions and List Comprehensions
- Conditionals within the List Comprehension
- Nested loops within the List Comprehensions in python
- Key points on List Comprehension
- More Examples of List Comprehension
Image Source: Google Images
What’s the Difference between List Comprehension and For Loop in Python?
Suppose, we wish to separate the letters of the word “analytics” and add the letters as items of a list. The primary thing that comes to mind would be using for loop.
Example 1: Using For loop to Iterate through a String
In this example, we will split the string based on characters and store all those characters in a new list.
However, Python has a better way to solve this issue using List Comprehension. List comprehension is a sublime way to define and make lists based on existing lists.
Let’s see how the above program may be written using list comprehensions.
Example 2: Using List Comprehension to Iterate through a String
separated_letters = [ letter for letter in 'analytics' ] print( separated_letters)
[ 'a', 'n', 'a', 'l', 'y', 't', 'i', 'c', 's' ]
In the above example, a brand new list is assigned to variable separated_letters, and the list contains the things of the iterable string ‘analytics’. Finally, to receive the output, we call the print() function of Python.
Syntax of List Comprehension
[expression for item in list]
Now, we are able to identify where list comprehensions are used.
If you noticed, “analytics” could be a string, not a list. This is often the facility of list comprehension. It can identify when it receives a string or a tuple and works on that as a list.
You can try this using loops. However, not every loop may be rewritten as a list comprehension. But as you learn and acquire comfortable with list comprehensions, You’ll end up replacing more and more loops with this elegant syntax.
List Comprehensions vs Lambda functions
To work or operations with the lists, List comprehensions aren’t the only way but various built-in functions and lambda functions can create and modify lists in fewer lines of code.
Example 3: Using Lambda functions inside List
letters = list(map(lambda y: y, 'analytics')) print(letters)
[ 'a', 'n', 'a', 'l', 'y', 't', 'i', 'c', 's' ]
In this code, we will separate the characters of the string using lambda functions.
However, in general list comprehensions are more human-readable than lambda functions. It’s easier to grasp what the programmer was trying to accomplish when list comprehensions are used.
Conditionals in List Comprehension
List comprehensions can utilize conditional statements to change the existing lists (or other tuples). we are going to create a list that uses mathematical operators, integers, and range().
Example 4: Using if with List Comprehension
even_list = [ i for i in range(10) if i % 2 == 0] print(even_list)
[0, 2, 4, 6, 8]
The list, even_list, is going to be populated by the things in the range from 0 – 9 if the item’s value is divisible by 2.
Example 5: Nested if with List Comprehension
filtered_list = [ x for x in range(50) if x % 2 == 0 if x % 5 == 0] print(filtered_list)
[0, 10, 20, 30, 40]
Here, list comprehension checks:
Is x divisible by 2 or not?
Is x divisible by 5 or not?
If x satisfies both conditions, x is appended to filtered_list.
Example 6: if…else With List Comprehension
list = ["even" if y%2==0 else "odd" for y in range(5)] print(list)
['even', 'odd', 'even', 'odd', 'even']
Here, list comprehension will check the five numbers from 0 to 4. If y is divisible by 2, then even is appended to the obj list. If not, odd is appended.
Nested Loops in List Comprehension
Suppose, we’d like to compute the transpose of a matrix that needs nested for loop. Let’s see how it’s done using normal for loop first.
Example 7: Finding Transpose of Matrix using Nested Loops
transposed_matrix =  matrix = [[1, 2, 3, 4], [4, 5, 6, 8]] for i in range(len(matrix)): transposed_row =  for row in matrix: transposed_row.append(row[i]) transposed_matrix.append(transposed_row) print(transposed_matrix)
[[1, 4], [2, 5], [3, 6], [4, 8]]
The above code uses two for loops to search out the transpose of the matrix.
Also, We can perform nested iterations inside a list comprehension. In this section, we are going to find the transpose of a matrix using a nested loop inside a list comprehension.
Example 8: Finding Transpose of a Matrix using List Comprehension
matrix = [[1, 2], [3,4], [5,6], [7,8]] transpose_matrix = [[row[i] for row in matrix] for i in range(2)] print (transpose_matrix)
[[1, 3, 5, 7], [2, 4, 6, 8]]
In the above program, we’ve got a variable matrix that has 4 rows and a couple of columns. We need to seek out the transpose of the matrix. For that, we used list comprehension.
Key Points on List Comprehension
The key points which we have to keep in mind while working with list comprehension are as follows:
- List comprehension is a sublime way to define and build lists with the help of existing lists.
- In comparison to normal functions and loops, List comprehension is usually more compact and faster for creating lists.
- However, we should always avoid writing very long list comprehensions in one line to confirm that code is user-friendly.
- Remember, every list comprehension is rewritten in for loop, but every for loop can’t be rewritten within the kind of list comprehension.
More Examples of List Comprehensions
Let’ see some more examples related to List Comprehension so that you have a better understanding of List Comprehensions in Python.
Example 9: Finding the elements in a list in which elements are ended with the letter ‘b’ and the length of that element is greater than 2
names = ['Ch','Dh','Eh','cb','Tb','Td','Chb','Tdb'] final_names = [name for name in names if name.lower().endswith('b') and len(name) > 2] final_names
In the above code, we use list comprehension with some conditions associated with it. The functions involved in the conditions are as follows:
- name. lower.endswith(‘b’): This function filter out all the strings from the list that are ended with the letters ‘b’ or ‘B’.
- len(name): This function finds the length of all the elements in a specified list.
Example 10: Reverse each String in a Tuple
# Reverse each elements in a specified tuple List = [string[::-1] for string in ('Hello', 'Analytics', 'Vidhya')] # Display the list print(List)
[ 'olleH', 'scitylanA', 'ayhdiV' ]
In the above code, we use the concept of slicing in a string, therefore by using the str[::-1] function, we can reverse the elements of a string, and we apply this function to every element in the tuple by using list comprehension.
This ends our discussion!
I hope you enjoyed the article.
If you want to connect with me, please feel free to contact me by Email.
Your suggestions and doubts are welcomed here in the comment section. Thank you for reading my article!
The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.