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
Python Lists
Python Tuples
Python Sets
Python Dictionary
Exercises & Assignments
Python program to find largest and smallest number in a list
Python program to remove duplicates from a list
Interview Questions & Answers
What is a list in Python?
What is a tuple in Python?
What is a set in Python?
What is a dictionary in Python?
What is a negative index in Python and why is it used?
What is the difference between a list and a tuple in Python?
What are mutable and immutable types in Python?