66. List Comprehensions
List Comprehensions: Creating lists in a concise, readable way
List comprehensions provide a powerful and syntactically elegant way to create and manipulate lists in Python. It allows you to build a new list by iterating over an iterable, optionally applying conditions or transformations to each item. Below are various examples showcasing the use of list comprehensions.
1. Basic List Comprehension
Creating a list of squares from an existing list.
Copy
# Traditional for-loop
squares = []
for i in range(5):
squares.append(i**2)
# List comprehension
squares = [i**2 for i in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]2. List Comprehension with Conditional Logic
You can add conditions to filter items during the iteration.
Copy
# List of even numbers from 0 to 9
evens = [i for i in range(10) if i % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]3. Applying Transformation with List Comprehension
You can apply a transformation to each item in the list.
Copy
4. List Comprehension with Multiple Iterators
You can use multiple for loops in a list comprehension.
Copy
5. Nested List Comprehensions
List comprehensions can also be nested to create more complex lists.
Copy
6. List Comprehension with Functions
You can also call functions inside list comprehensions to transform data.
Copy
7. List Comprehension with Conditional Expressions
You can use conditional expressions to modify the list items during iteration.
Copy
8. List Comprehension for Filtering Even Numbers
List comprehensions can be used for filtering and creating a new list based on a condition.
Copy
9. Creating a List of Tuples
You can create a list of tuples using list comprehensions.
Copy
10. List Comprehension for Dictionary Keys
You can use list comprehensions to generate keys for dictionaries or lists of dictionary items.
Copy
Summary of Features:
Basic iteration:
[expression for item in iterable]Filtering:
[expression for item in iterable if condition]Multiple iterators:
[expression for item1 in iterable1 for item2 in iterable2]Nested list comprehensions: Used for flattening or transforming nested data structures.
Function calls: Functions can be applied within list comprehensions to modify or transform the data.
Conditional expressions: Apply conditional logic (
if-else) within the comprehension to modify list items.
List comprehensions enhance the readability and conciseness of your Python code, making it easier to perform complex iterations, transformations, and filtering on iterables.
Last updated