For Loops and List Comprehension in Python

For Loops and List Comprehension in Python

What are For Loops?

for loops are traditionally used when you have a block of code which you want to repeat a fixed number of times. The Python for statement iterates over the members of a sequence in order, executing the block each time. Source

Can you guess the output?

for loop in python

 

A for loop is a control flow statement that allows repeated execution of a block of code a fixed number of times. In the above example, line 2 is executed once for each apple in the list. Therefore the output can be visualized as:

Apple1
Apple2
Apple3
Apple4

Thus, the variable ‘apple’ present in line 1 and line 2 changes value for each element in the list.

Can you guess the output?

learn python

In case you’re stuck, have a look at the documentation for the range function.

List Comprehension

What is List Comprehension in python?

List Comprehension is an alternative method of writing for loops in a more efficient manner.

Here’s an example of using the list comprehension instead of a basic for loop:

Learn list comprehension

List Comprehension does a lot more than being syntactical sugar. Let’s compare the two methods using the time it functions from the inbuilt time module.

learnpython

learn python

Don’t sweat if you do not understand any of the stuff above. The only concern should be to understand the result of this analysis.

While both the programs perform similar functions, the major difference lies in the way append lookup that happens for the list.
In the “list comprehension” example, a specialized LIST_APPEND bytecode is generated to perform a faster append into the list. Thus, list comprehensions avoid redundant repetitions of function definition lookup in the loop. Bottom-line, List Comprehension is much faster as compared to normal for loop execution. Here’s a short piece of code that flattens a 2D list-

res=[]
for I in [[1,2,3],][2,3],[1]]:
	for j in i:
		res.append(j)

The same task can be done much more efficiently by list comprehension with the line

res=[j for i in [[1,2,3],][2,3],[1]] for j in i]

Another cool feature of the list comprehension is that it allows if and else statements in it. For example

res=[j if (j<2) else 'too much' for i in lst for j in i]

would bring the value of the result to [1, ‘too much’, ‘too much’]. This marks the end of this article, Do comment your Feedback.

Leave a Comment

Your email address will not be published. Required fields are marked *

Share This
Scroll to Top