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:
Image Source: Google Images
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.
separated_letters = []
for letter in 'analytics':
separated_letters.append(letter)
print(separated_letters)
Code Explanation:
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.
separated_letters = [ letter for letter in 'analytics' ] print( separated_letters)
Output:
[ 'a', 'n', 'a', 'l', 'y', 't', 'i', 'c', 's' ]
Code Explanation:
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.
[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.
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.
letters = list(map(lambda y: y, 'analytics')) print(letters)
Output:
[ 'a', 'n', 'a', 'l', 'y', 't', 'i', 'c', 's' ]
Code Explanation:
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.
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().
even_list = [ i for i in range(10) if i % 2 == 0] print(even_list)
Output:
[0, 2, 4, 6, 8]
Code Explanation:
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.
filtered_list = [ x for x in range(50) if x % 2 == 0 if x % 5 == 0] print(filtered_list)
Output:
[0, 10, 20, 30, 40]
Code Explanation:
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.
list = ["even" if y%2==0 else "odd" for y in range(5)] print(list)
Output:
['even', 'odd', 'even', 'odd', 'even']
Code Explanation:
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.
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.
transposed_matrix = [] matrix = [[1, 2, 3, 4], [4, 5, 6, 8]] for i in range(len(matrix[0])): transposed_row = [] for row in matrix: transposed_row.append(row[i]) transposed_matrix.append(transposed_row) print(transposed_matrix)
Output:
[[1, 4], [2, 5], [3, 6], [4, 8]]
Code Explanation:
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.
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)
Output:
[[1, 3, 5, 7], [2, 4, 6, 8]]
Code Explanation:
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.
The key points which we have to keep in mind while working with list comprehension are as follows:
Let’ see some more examples related to List Comprehension so that you have a better understanding of List Comprehensions in Python.
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
Output:
['Chb', 'Tdb']
Code Explanation:
In the above code, we use list comprehension with some conditions associated with it. The functions involved in the conditions are as follows:
# Reverse each elements in a specified tuple List = [string[::-1] for string in ('Hello', 'Analytics', 'Vidhya')] # Display the list print(List)
Output:
[ 'olleH', 'scitylanA', 'ayhdiV' ]
Code Explanation:
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.
Example 8 is not working, and the explanation is not an explanation but the description of the task. Please provide the solution. Thanks a lot
Thank you so much for writing this! A lot of lessons on list comprehensions don't go into the advanced things you can do with it but this did which was very useful. Thanks again!