For Loop vs List Comprehension
There are some different ways you can create a list in python. List comprehension offers a shorter syntax when you want to create a new list. You could rewrite the for
loop from the example below in just a single line of code:
Let’s do the same example with the help from list comprehension:
Every list comprehension in Python includes three elements:
list = [expression for member in iterable]
expression
is a call to a method, or any other valid expression that returns a value. In the example above, the expression is x**2.member
is the object or value in the list or iterable. In the example above, the member value is x.iterable
is a list, set, or any other object that can return its elements one at a time. In the example above, the iterable isrange(0,50)
.
By using For Loop, we can copy the elements of the existing list in our new and empty list and this way is the most popular approach.
Output:
['red', 'pink', 'blue', 'white']
Now let’s do our code to compressed into a single line with help from list comprehension.
List Comprehension have various advantages according to for loop approach. This is a fast and simple way for assigning elements to the list.
Some benefits of using list comprehension
- Less Code Required : With List Comprehension, your code gets compressed from 3–4 lines to just 1 line.
- Easy to Understand: Compared to normal for loop approach, list comprehension is easier to understanding and implementation. Using list comprehension your code becomes readable for other programmers.
- Better Performance : Compared to the normal for loop approach, list comprehension boosts the performance of your program.
SOME EXAMPLES
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Output:
[1, 4, 7]