DEV Community

Cover image for Python Trick: Using List Comprehensions with Conditional Logic
Developer Service
Developer Service

Posted on

Python Trick: Using List Comprehensions with Conditional Logic

List comprehensions in Python are a concise way to create lists and allow conditional logic to filter or modify elements based on certain criteria.

This can lead to cleaner and more readable code.

Example: Filtering and Modifying List Items

# Original list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use list comprehension to create a new list with even numbers squared
squared_evens = [x**2 for x in numbers if x % 2 == 0]

print("Squared even numbers:", squared_evens)


# Output
# Squared even numbers: [4, 16, 36, 64, 100]
Enter fullscreen mode Exit fullscreen mode

How It Works:

  • [x*2 for x in numbers if x % 2 == 0] is a list comprehension that iterates over numbers, checks if each number is even (x % 2 == 0), and if so, square it (x*2).
  • The result is a new list containing only the squared values of the even numbers from the original list.

Why It’s Cool:

  • Conciseness: Allows you to write more compact and readable code than traditional loops and conditionals.
  • Readability: It makes it easy to see the intent of the code (filtering and transforming) in a single line.
  • Efficiency: This can be more efficient than using multiple loops and conditionals.

This trick is handy for any task that involves filtering and transforming data in a list, such as data processing or preparation.

Top comments (0)