List comprehension vs for loop in python

 LIST COMPREHENSION VS FOR-LOOP IN PYTHON.

So a friend introduces me to a python feature called list comprehension that requires me to use a single line code to solve a problem that could be still solved with multiple lines with a for loop or a function.

How do these two techniques differ?

Python has an alternative way to solve this issue using List Comprehension.
List comprehension is a better way to define one list in terms of an existing list.

Example 1:Finding the squares of numbers in a certain range using list comprehension and a for a loop.

Both of these techniques will give the same output.

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


List comprehension comes with benefits and when to use it with the help of solving other technical challenges.

List comprehension is a tool that can be used in different situations. List comprehension can be used for mapping and filtering.

Below, are two filtering techniques restricted to give an output of even squares. Both the list comprehension and for loop use the same condition and give the same output.


Example 2

#List comprehension: filtering
even_squares = [x * x for x in range(10) if x % 2 == 0]
even_squares



#For loop:filtering
even_squares = []
for x in range(10):
    if x % 2 == 0:
        even_squares.append(x*x)
even_squares


These give the same output

[0, 4, 16, 36, 64]

Keynotes:

  • List comprehension proves to be faster than normal functions and loops for creating lists.
  • However, since list comprehension takes a single line code. We should avoid writing very long lines to ensure that code is user-friendly.
  • Note, every list comprehension can be rewritten in for loop, but every for loop can't be rewritten in the form of list comprehension.
Let me how you find the two python techniques...

Comments