List Comprehension in Python

Table of contents
List comprehension in Python is a concise way to create lists. It allows you to generate a new list by applying an expression to each item in an existing list or iterable, often using a for-loop and optional conditionals, all in a single line of code.
Here's a simple example:
# Traditional way
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension way
squares = [x**2 for x in range(10)]
print(squares)
result:
Python List Comprehension Syntax:
expression: The value to include in the new list.
item: The variable representing each element in the iterable.
iterable: The collection of items you are looping through.
condition (optional): A filter that determines which items to include.
returns: a new list that is created based on the specified expression, for each item in the given iterable, and optionally filtered by a condition.
Subscribe to my newsletter
Read articles from MOWMITA directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
