Do the same but faster

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.

Basic structure of list comprehension (image by author)

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]

#python #programming #how to convert loops to list comprehension in python #convert loops #list comprehension #how to convert loops to list comprehension

How to Convert Loops to List Comprehension in Python
1.30 GEEK