0% found this document useful (0 votes)
5 views2 pages

List Comprehension Python

List comprehension in Python is a concise way to create lists by applying an expression to each item in an iterable, with optional filtering. It has a basic syntax and can include conditions, nested comprehensions, and even else conditions. Key advantages include cleaner code and improved performance, but it should be avoided when readability suffers or logic becomes too complex.

Uploaded by

Somansh Rastogi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

List Comprehension Python

List comprehension in Python is a concise way to create lists by applying an expression to each item in an iterable, with optional filtering. It has a basic syntax and can include conditions, nested comprehensions, and even else conditions. Key advantages include cleaner code and improved performance, but it should be avoided when readability suffers or logic becomes too complex.

Uploaded by

Somansh Rastogi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

List Comprehension in Python

List comprehension is a concise way to create lists in Python.

It allows you to generate a new list by applying an expression to each item in an iterable,

optionally filtering items with a condition.

Basic Syntax:

[expression for item in iterable]

Example:

squares = [x*x for x in range(5)]

# Output: [0, 1, 4, 9, 16]

List Comprehension with Condition:

[expression for item in iterable if condition]

Example:

even_numbers = [n for n in range(10) if n % 2 == 0]

# Output: [0, 2, 4, 6, 8]

Nested List Comprehension:

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

# Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

With Else Condition:

["even" if x % 2 == 0 else "odd" for x in range(5)]

# Output: ["even", "odd", "even", "odd", "even"]

Key Advantages:

- More concise and cleaner code

- Often faster than traditional loops

- Easy to include conditions and transformations

When NOT to Use:

- When resulting code becomes hard to read

- When logic is too complex; better use loops

You might also like