Member-only story

Master Python List Comprehensions: Compact and Readable

Boost your Python skills with this powerful technique for writing concise, expressive code

Max N
2 min readApr 4, 2024
Photo by Jotaefe on Unsplash

List comprehensions are a powerful feature in Python that allow you to create lists in a concise and expressive way. They can make your code more readable and easier to maintain, especially when working with lists and sequences. Let’s dive into some examples and see how they can enhance your Python skills.

Basic List Comprehension

Suppose you want to create a list of squared numbers from a list of numbers. Instead of using a traditional for loop:

numbers = [1, 2, 3, 4, 5]
squared_numbers = []

for num in numbers:
squared_numbers.append(num ** 2)

print(squared_numbers) # Output: [1, 4, 9, 16, 25]

You can use a list comprehension to achieve the same result in a single line:

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]

print(squared_numbers) # Output: [1, 4, 9, 16, 25]

The list comprehension [num ** 2 for num in numbers] creates a new list by squaring each number in the numbers list.

Conditional List Comprehensions

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet