This post was made public as part of the Data Science Blogathon
Introduction
In this post, we will study the lists by understanding of Python and how to use them. The topics that we will discuss in this post are the following:
- What is 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 list comprehension
- Nested loops within the list of comprehensions in Python
- Key points about understanding lists
- More list comprehension examples

Image source: Google Images
What is the difference between list comprehension and for loop in Python?
Suppose we yearn to separate the letters of the word “analysis” and add the letters as items from a list. The main thing that comes to mind would be to use for loop.
Example 1: using the For loop to iterate through a string
separated_letters = [] for letter in 'analytics': separated_letters.append(letter) print(separated_letters)
Production:
[ 'a', n, 'a', 'l', 'y', 't', 'i', 'c', 's' ]
Explanation of the code:
In this example, we will split the string based on the characters and store all those characters in a new list.
Despite this, Python has a better way to solve this problem using List Comprehension. List comprehension is a sublime way of establishing and making lists based on existing lists..
Let's see how the above program can be written using comprehension lists.
Example 2: using list comprehension to iterate through a string
separated_letters = [ letter for letter in 'analytics' ] print( separated_letters)
Production:
[ 'a', n, 'a', 'l', 'y', 't', 'i', 'c', 's' ]
Explanation of the code:
In the example above, a new list is assigned to the letter_separated variables, and the list contains the things of the iterable string ‘analysis’. To end, to receive the exit, we call the Print() python function.
List Comprehension Syntax
[expression for item in list]
Now, we can identify where lists are used by understanding.
If he realized, “analysis” could be a string, not a list. This is often the easy to understand lists. You can identify when you receive a string or a tuple and work on that as a list.
You can test this using loops. Despite this, not all loops can be rewritten as a comprehension list. But as you learn and get comfortable with comprehension lists, you'll end up replacing more and more loops with this fancy syntax.
List of understandings vs Lambda functions
To work or perform operations with lists, comprehension lists are not the only way, but various built-in tools and lambda functions can create and modify lists in fewer lines of code.
Example 3: using Lambda functions inside List
letters = list(map(lambda and: Y, 'analytics')) print(letters)
Production:
[ 'a', n, 'a', 'l', 'y', 't', 'i', 'c', 's' ]
Explanation of the code:
In this code, we will separate the characters from the string using lambda functions.
Despite this, in general, comprehension lists are more human readable than lambda functions. It is easier to understand what the programmer was trying to achieve when using comprehension lists.
Conditionals in understanding lists
Comprehensive lists can use conditional statements to change existing lists (or other tuples). let's create a list that uses mathematical operators, integers and range ().
Example 4: Use if with list comprehension
even_list = [ i for i in range(10) if i % 2 == 0] print(even_list)
Production:
[0, 2, 4, 6, 8]
Explanation of the code:
The list, even_list, will be completed with things in the range of 0 a 9 if the value of the element is divisible by 2.
Example 5: nested yes with list comprehension
filtered_list = [ x for x in range(50) if x % 2 == 0 if x % 5 == 0] print(filtered_list)
Production:
[0, 10, 20, 30, 40]
Explanation of the code:
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 added 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)
Production:
['even', 'odd', 'even', 'odd', 'even']
Explanation of the code:
Here, understanding the list will verify the five numbers of the 0 al 4. If y is divisible by 2, par is added to obj list. If that is not the case, odd is added.
Nested loops in list comprehension
Suppose we would like to compute the transpose of an array that needs a nested for loop. Let's see how it's done using the normal for loop first.
Example 7: find matrix transpose using nested loops
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)
Production:
[[1, 4], [2, 5], [3, 6], [4, 8]]
Explanation of the code:
The above code uses two for loops to find the transpose of the matrix.
At the same time, we can do nested iterations within a comprehension list. In this section, we are going to find the transposition of a matrix using a nested loop within a comprehension list.
Example 8: Finding the transposition of a matrix through 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)
Production:
[[1, 3, 5, 7], [2, 4, 6, 8]]
Explanation of the code:
In the above program, tenemos una matriz variableIn statistics and mathematics, a "variable" is a symbol that represents a value that can change or vary. There are different types of variables, and qualitative, that describe non-numerical characteristics, and quantitative, representing numerical quantities. Variables are fundamental in experiments and studies, since they allow the analysis of relationships and patterns between different elements, facilitating the understanding of complex phenomena.... what's wrong with it 4 rows and a couple of columns. We need to find the transpose of the matrix. For that, we use list comprehension.
Key points in understanding lists
The key points to pay attention to when working with list comprehension are as follows:
- List comprehension is a sublime camino to establish and build lists with the help of existing lists.
- Compared to normal loops and functions, list comprehension It is usually more compact and faster to create lists.
- Despite this, we should always Avoid writing very long comprehensive lists on one line. to confirm that code is easy to use.
- Remember, each comprehension list it is rewritten in for loop, but all for loops cannot be rewritten within more or less list comprehension.
More list comprehension examples
Let's look at some more examples related to list comprehension so that you have a better understanding of list comprehensions in Python.
Example 9: Find the items in a list in which the items end 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
Production:
['Chb', 'Tdb']
Explanation of the code:
In the above code, we use list comprehension with some associated conditions. The functions involved in the conditions are as follows:
- Name. lower.endswith (‘b’): This function filters all the strings in the list that end with the letters' b’ o ‘B’.
- len (Name): This function finds the length of all items in a specified list.
Example 10: invert each string into a tuple
# Reverse each elements in a specified tuple
List = [string[::-1] for string in ('Hello', 'Analytics', 'Vidhya')]
# Display the list
print(List)
Production:
[ 'olleH', 'scitylanA', 'ayhdiV' ]
Explanation of the code:
In the above code, we use the concept of cutting into a chain, therefore, when using str[::-1] function, we can invert the items of a string, and we apply this function to each element in the tuple using list comprehension.
This ends our discussion!!
Final notes
I hope you enjoyed the post.
If you want to connect with me, Do not doubt to keep in touch with me. by Email.
Your suggestions and doubts are welcome here in the comments section. Thanks for reading my post!!
The media shown in this post is not the property of DataPeaker and is used at the author's discretion.



