List comprehensions in Python provide a powerful and concise way to create lists. They are an essential part of any Python programmer's toolkit. Ready to make your code more Pythonic? Let's dive in!
What is a List Comprehension?
A list comprehension is a compact way to process all or part of the elements in a sequence and return a list with the results. The syntax is simple yet powerful:
[expression for item in iterable if condition]
Basic Example
Let's start with a basic example. Suppose we want a list of squares for numbers from 0 to 9. With list comprehensions, it's a one-liner:
squares = [x**2 for x in range(10)]
print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Adding a Condition
What if we want only even squares? Just add an if condition at the end:
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
Output:
[0, 4, 16, 36, 64]
Nested Comprehensions
You can also nest comprehensions for multidimensional lists. Here’s an example to flatten a 2D list:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionary Comprehensions
List comprehensions aren’t just for lists. You can create dictionaries too!
squares_dict = {x: x**2 for x in range(10)}
print(squares_dict)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Set Comprehensions
And even sets! This creates a set of unique squares:
unique_squares = {x**2 for x in range(10)}
print(unique_squares)
Output:
{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
Advanced Use - Function Application
You can apply functions within comprehensions. Here’s an example using str.upper():
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words)
Output:
['HELLO', 'WORLD', 'PYTHON']
Comprehensions with Multiple Conditions
You can add multiple conditions. Let’s filter numbers divisible by 2 and 3:
filtered = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]
print(filtered)
Output:
[0, 6, 12, 18]
In Conclusion
List comprehensions make your code cleaner and more readable. They’re efficient and Pythonic. Practice and integrate them into your projects to see the magic!
0 Comments:
Post a Comment