For Loop vs List Comprehension

Why we use a list comprehension?

Photo by Claire Satera on Unsplash

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:

https://thagomizer.com/

Every list comprehension in Python includes three elements:

list = [expression for member in iterable]
  1. 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.
  2. member is the object or value in the list or iterable. In the example above, the member value is x.
  3. iterable is a list, set, or any other object that can return its elements one at a time. In the example above, the iterable is range(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

https://www.thecoderpedia.com/
  1. Less Code Required : With List Comprehension, your code gets compressed from 3–4 lines to just 1 line.
  2. 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.
  3. 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]

Computer Engineering

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store