List compression
List compression in Python
Section titled “List compression in Python”List compression is a concise and elegant way to create lists from other sequences (lists, tuples, ranges, etc.) by applying transformations or filters in a single line of code.
Why use list compression?
Section titled “Why use list compression?”- Lets you write more readable and clean code.
- Is more efficient than using traditional loops to create lists.
- Facilitate applying conditions and transformations to elements.
Basic syntax
Section titled “Basic syntax”The general syntax is:
[new_expression for element in sequence if condition]
new_expression
: what you want to add to the new list.element
: each value from the original sequence.sequence
: the collection of data to iterate over.condition
(optional): filters the elements that meet the condition.
Simple example
Section titled “Simple example”Suppose you want to obtain a list with the squares of numbers from 1 to 5:
squares = [x**2 for x in range(1, 6)]print(squares)
Output:
[1, 4, 9, 16, 25]
Example with condition (filter)
Section titled “Example with condition (filter)”Now, we only want the squares of even numbers:
squares_even = [x**2 for x in range(1, 6) if x % 2 == 0]print(squares_even)
Output:
[4, 16]
Comparison with traditional loops
Section titled “Comparison with traditional loops”The following code does the same, but using a for
loop:
squares = []for x in range(1, 6):squares.append(x**2)
As you can see, list comprehension is more compact and easier to read.
Summary
Section titled “Summary”- List comprehension allows you to create new lists concisely and efficiently.
- You can transform and filter elements in a single line.
- It is a powerful tool for working with collections in Python.
Are you ready to practice? Try creating a list with the odd numbers from 1 to 20 using list comprehension. .