How to Convert Loops to List Comprehensions in Python | by Soner Yıldırım | Towards Data Science

List comprehension is used for creating lists based on iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops.
The syntax of a list comprehension is actually easy to understand. However, when it comes to complex and nested operations, it might get a little tricky to figure out how to structure a list comprehension.
In such cases, writing the loop version first makes it easier to write the code for the list comprehension. We will go over several examples that demonstrate how to convert a loop-wise syntax to a list comprehension.
Let’s start with a simple example. We have a list of 5 integers and want to create a list that contains the squares of each item. Following is the for loop that performs this operation.
lst_a = [1, 2, 3, 4, 5]lst_b = []for i in lst_a:   lst_b.append(i**2)print(lst_b)[1, 4, 9, 16, 25]
The list comprehension version of the same task:
lst_b = [i**2 for i in lst_a]print(lst_b)[1, 4, 9, 16, 25]
We already notice how the list comprehension simplifies the syntax. It serves as a powerful one-liner. The figure below illustrates the conversion.
The list comprehension starts with the final operation. Then, we place the line that defines the for loop.
The operation placed in a list comprehension can be more complex than a single math operation. Consider the following list of names.
names = ["John Doe", "Jane Doe", "Mike Fence"]
We would like to create a list that contains only the first names. Here is the loop that accomplishes this task:
first_names = []for name in names:   first_names.append(name.split(" ")[0])print(first_names)['John', 'Jane', 'Mike']
We first split the name string at the space character and then take the first word. It is quite similar to the previous example to convert this loop to a list comprehension.
first_names = [name.split(" ")[0] for name in names]print(first_names)['John', 'Jane', 'Mike']
We can also place conditional statements in a list comprehension. Let’s repeat the previous example but with a condition. The list of first names will only contain names that start with the letter j.
first_names = []for name in names:   if name.startswith("J"):      first_names.append(name.split(" ")[0])print(first_names)['John', 'Jane']
We use the startswith method to apply the desired condition. The same condition is added to a list comprehension as follows.
first_names = [name.split(" ")[0] for name in names if name.startswith("J")]print(first_names)['John', 'Jane']
The following figure demonstrated the conversion.
We put the final operation at the beginning of the list comprehension. Then, we follow the lines from the top to the bottom as indicated with the colored box.
If you follow this logic, you can easily convert complex loops to a list comprehension. Let’s finish up with a slightly more complicated examples. Consider the following list of 3 lists.
lst_a = [[4,3,5], [1,5,3,8], [1,6,2,4]]
We want to create a new list that contains the all the numbers from the nested lists that are greater than 3.
mylist = []for lst in lst_a:   for item in lst:      if item > 3:         mylist.append(item)print(mylist)[4, 5, 5, 8, 6, 4]
The list comprehension that performs this task is:
mylist = [item for lst in lst_a for item in lst if item > 3]
Although this loop is more complicated than the previous ones, the logic to convert it to a list comprehension is the same.
It starts with the last operation in the loop. Then, we follow the loop from the top to the bottom. Each line in the loop is placed in the comprehension consecutively.
List comprehensions are faster than loops in general. It achieves to be faster by loading the entire list into the memory.
There is a downside of this approach when working with large lists (e.g. 1 billion elements). It may cause your computer to crash due to the extreme amount of memory requirement.
A better alternative for such large lists is using a generator that does not actually create a large data structure in memory. A generator creates items as they are called.
Thank you for reading. Please let me know if you have any feedback.