List Comprehension

3 min read ·

List comprehension is a concise and powerful way to create new lists from existing iterables. It allows you to write clean, readable, and efficient code in a single line.
List comprehensions are widely used in data processing, filtering, and transformations.

What Is List Comprehension?

List comprehension provides a shorter syntax for creating a list using a loop.

Basic Syntax

Example:

List Comprehension vs Traditional Loop

Using for Loop


Using List Comprehension


List Comprehension with Condition

You can filter items using a condition.

Syntax


List Comprehension with if-else

You can use conditional expressions.

Syntax


Nested List Comprehension

Used for working with nested lists.

List Comprehension with Strings


List Comprehension with Functions


List Comprehension with range()


Modify Existing List Using Comprehension


Using List Comprehension with Conditions Only


Common Mistakes

Wrong Order of if

Correct:

Overusing List Comprehensions

Avoid using them when logic becomes complex.

Performance Insight

  • List comprehensions are generally faster than loops
  • They use less memory overhead
  • Best for simple transformations