List comprehension vs while and for loop in python | applied electronics engineering

Latest

List comprehension vs while and for loop in python

By Applied Electronics - Tuesday, July 19, 2016 No Comments
When you want to do something iteratively such as printing out the items stored in a list you can do this using while and for loop. But you can also do the same thing using list comprehension. List comprehension is a shorter and the preferred method in python.

But to show how the approaches looks in code we start with the while and for loop.

Consider that you have a list of some items and you wanted to perform some operation on the items, for example, print out the items.

Using while loop you would do this as follows:

L = ['jon', 'micheal', 'romeo']

index = 0

while index < len(L):
    item = L[index]
    print(item)
    index += 1

In the above python code, L is the list which contains 3 names. Then using an initialized variable index we use the while loop to check the condition that until the index is less than the number of items in the list we iteratively print out the items. The output of this python code is as follows:

jon
micheal
romeo

Next consider doing the same thing using for loop.

L = ['jon', 'micheal', 'romeo']

for k in L:
    print(k)

The code using the python for loop is even shorter. In the code k is just a variable that refers to the items of the list L. In the first pass of the loop, k is jon, in the second pass, k is micheal and in the third it is romeo. The output is the same as for while loop as follows:

jon
micheal
romeo

When you compare while and for loop code you can see that for loop is shorter but list comprehension is even more shorter. To do the same thing as above using list comprehension we write as follows:

L = ['jon', 'micheal', 'romeo']
   
[print(k) for k in L]

The output is the same as before:

jon
micheal
romeo

As you can see, the List comprehension code is even shorter than for code which in turn is shorter than while code.


No Comment to " List comprehension vs while and for loop in python "