What is list comprehension in Python?

List comprehension is a short way to create a new list in a single line. The syntax is [expression for item in iterable if condition].

squares = [x * x for x in range(1, 6)]
print(squares)

evens = [x for x in range(10) if x % 2 == 0]
print(evens)

Output:

Tutorials Class - Output Window

[1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]

The same work with a normal loop needs three or four lines:

squares = []
for x in range(1, 6):
    squares.append(x * x)

Comprehensions are shorter and usually a bit faster, but keep them simple. If the line becomes hard to read, use a normal loop. Python also has dictionary and set comprehensions. See Python for loop.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.