Comprehensions in Python (original) (raw)
Comprehensions in Python provide a short and clear way to create new sequences from existing iterables.
- Improve readability by replacing long loops with a single statement.
- Encourage modular and clean coding practices.
- Commonly used in data processing, web development, and automation tasks.
- Reduce errors by minimizing lines of code.
- Work well with functions like zip(), enumerate(), map(), and lambda.
Types of Comprehensions in Python
Python provides different types of comprehensions that simplify the creation of data structures in a clean and readable manner. Each type is explained below with simple examples.
1. List Comprehensions
List comprehensions allow for the creation of lists in a single line, improving efficiency and readability. They follow a specific pattern to transform or filter data from an existing iterable.
**Syntax:
[expression for item in iterable if condition]
- **expression: Operation applied to each item.
- **item: Variable representing the element from the iterable.
- **iterable: The source collection.
- **condition (optional): A filter to include only specific items.
**Example 1: Generating a list of even numbers
Python `
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] res = [num for num in a if num % 2 == 0] print(res)
`
**Explanation: This creates a list of even numbers by filtering elements from a that are divisible by 2.
**Example 2: Creating a list of squares
Python `
res = [num**2 for num in range(1, 6)] print(res)
`
**Explanation: This generates a list of squares for numbers from 1 to 5.
2. Dictionary comprehension
Dictionary Comprehensions are used to construct dictionaries in a compact form, making it easy to generate key-value pairs dynamically based on an iterable.
**Syntax:
{key_expression: value_expression for item in iterable if condition}
- **key_expression: Determines the dictionary key.
- **value_expression: Computes the value.
- **iterable: The source collection.
- **condition (optional): Filters elements before adding them.
**Example 1: Creating a dictionary of numbers and their cubes
Python `
res = {num: num**3 for num in range(1, 6)} print(res)
`
Output
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
**Explanation: This creates a dictionary where keys are numbers from 1 to 5 and values are their cubes.
**Example 2: Mapping states to capitals
Python `
a = ["Texas", "California", "Florida"] # states b = ["Austin", "Sacramento", "Tallahassee"] # capital
res = {state: capital for state, capital in zip(a, b)} print(res)
`
Output
{'Texas': 'Austin', 'California': 'Sacramento', 'Florida': 'Tallahassee'}
**Explanation: zip() function pairs each state with its corresponding capital, creating a dictionary.
3. Set comprehensions
Set Comprehensions are similar to list comprehensions but result in sets, automatically eliminating duplicate values while maintaining a concise syntax.
**Syntax:
{expression for item in iterable if condition}
- **expression: The operation applied to each item.
- **iterable: The source collection.
- **condition (optional): Filters elements before adding them.
**Example 1: Extracting unique even numbers
Python `
a = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
res = {num for num in a if num % 2 == 0} print(res)
`
**Explanation: This creates a set of even numbers from **a, automatically removing duplicates.
**Example 2: Creating a set of squared values
Python `
res = {num**2 for num in range(1, 6)} print(res)
`
**Explanation: This generates a set of squares, ensuring each value appears only once.
3. Generator comprehensions
Generator Comprehensions create iterators that generate values lazily, making them memory-efficient as elements are computed only when accessed.
**Syntax:
(expression for item in iterable if condition)
- **expression: Operation applied to each item.
- **iterable: The source collection.
- **condition (optional): Filters elements before including them.
**Example 1: Generating even numbers using a generator
Python `
res = (num for num in range(10) if num % 2 == 0) print(list(res))
`
**Explanation: This generator produces even numbers from 0 to 9, but values are only computed when accessed.
**Example 2: Generating squares using a generator
Python `
res = (num**2 for num in range(1, 6)) print(tuple(res))
`
**Explanation: The generator creates squared values on demand and returns them as a tuple when converted.