Skip to content
Python

List Comprehension

Quickly generate lists using list comprehensions.

By EZ4Code Team
listcomprehension

Code

# Generate list of squares
squares = [x**2 for x in range(10)]
print(squares)

# Conditional comprehension
evens = [x for x in range(20) if x % 2 == 0]

# Nested comprehension
matrix = [[i * j for j in range(3)] for i in range(3)]

# Dict comprehension
word_len = {w: len(w) for w in ["hello", "world", "python"]}

Explanation

List comprehensions are syntactic sugar for concisely creating lists in Python.

More Python Snippets