C
h
i
L
L
u
.
.
.
Back to ArticlesPython List Comprehensions ExplainedPython

Python List Comprehensions Explained

avatarSombir RedhuMar 8, 20263 min read88
pythonlistscomprehensionbeginner

A list comprehension is a compact way to create a list from another iterable. Instead of writing a loop, you can write a single line.

# Traditional loop\nsquares = []\nfor i in range(10):\n    squares.append(i ** 2)\n\n# List comprehension\nsquares = [i ** 2 for i in range(10)]\n\n# With condition\nevens = [i for i in range(20) if i % 2 == 0]

You can also use nested list comprehensions for 2D structures, but keep readability in mind — if it becomes hard to read, a regular loop is better.

Sponsored

Comments0

?

No comments yet. Be the first!