List comprehension in Python

Sooraj Parakkattil
3 min readJun 21, 2020
Photo by Mitchell Luo on Unsplash

Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a subsequence of those elements that satisfy a certain condition.

  • List comprehension is an elegant way to define and create lists based on existing lists.
  • List comprehension is generally more compact and faster than normal functions and loops for creating a list.
  • However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.
  • Remember, every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.

It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists.

The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

The list comprehension always returns a resultant list

If you used to do it like this:

new_list = []
for i in old_list:
if filter(i):
new_list.append(expressions(i))
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))

You can obtain the same thing using list comprehension:

new_list = [expression(i) for i in old_list if filter(i)]squares = list(map(lambda x: x**2, range(10)))#OR
squares = [x**2 for x in range(10)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

The list comprehension starts with a ‘[‘ and ‘]’, to help you remember that the result is going to be a list.

The basic syntax is

[ expression for item in list if conditional ]

This is equivalent to:

--

--

Sooraj Parakkattil

All things product. Web, python and dipping my toes into machine learning.