DEV Community

jkaplan15
jkaplan15

Posted on

List Comprehension in Python

What is List Comprehension:

List comprehension is a syntactic construct in Python that allows you to create new lists by iterating over existing iterables, applying conditions, and performing transformations in a single line of code. It combines the functionality of a for loop, conditional statements, and expressions into a compact and expressive form.

List Comprehension Syntax:

new_list = [expression for item in iterable if item condition]
Enter fullscreen mode Exit fullscreen mode
  • new_list: The resulting list that will be created based on the comprehension.

  • expression: The expression or operation applied to each item.

  • item: The variable representing each item in the iterable.

  • iterable: The existing iterable (e.g., list, tuple, string) that is being iterated over.

  • condition (optional): A condition that filters items based on a given criteria.

Examples:

  1. Squaring numbers using list comprehension:

Input:

numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared)
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode
  1. Filtering out odd numbers using list comprehension:

Input:

numbers = [1, 2, 3, 4, 5]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)

Enter fullscreen mode Exit fullscreen mode

Output:

[2, 4]
Enter fullscreen mode Exit fullscreen mode

Benefits of List Comprehension:

  • Concise and readable code: List comprehension condenses multiple lines of code into a single line, making it easier to read and understand.

  • Efficiency: List comprehension is often faster than traditional loops since it takes advantage of Python's underlying optimizations.

  • Reduces code duplication: By performing operations in a single line, list comprehension reduces the need for temporary variables and repetitive code.

Conclusion:

List comprehension is a powerful feature in Python that allows you to create new lists based on existing iterables, apply conditions, and perform transformations in a concise and readable manner. It offers a compact syntax that simplifies your code and improves efficiency. By mastering list comprehension, you can write cleaner and more expressive Python code.

Top comments (0)