Comprehensions in Python provide a concise and efficient way to create new sequences from existing ones. They enhance code readability and reduce the need for lengthy loops. Python supports four types of comprehensions:
- List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
- Generator Comprehensions
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]
Where:
- 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.
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}
Where:
- 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.
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}
Where:
- 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.
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)
Where:
- 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.
Similar Reads
List Comprehension in Python
List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
Python Dictionary Comprehension
Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are iter
4 min read
Nested List Comprehensions in Python
List Comprehension are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Neste
5 min read
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other value. In any programming language, an expression is evaluated as per the precedence of its operators. So that if there is more than one operator in an expression, their precedence decides which operat
5 min read
Map vs List comprehension - Python
List comprehension and map() both transform iterables but differ in syntax and performance. List comprehension is concise as the logic is applied in one line while map() applies a function to each item and returns an iterator and offering better memory efficiency for large datasets.List comprehensio
2 min read
Break a list comprehension Python
Python's list comprehensions offer a concise and readable way to create lists. While list comprehensions are powerful and expressive, there might be scenarios where you want to include a break statement, similar to how it's used in loops. In this article, we will explore five different methods to in
2 min read
Python Naming Conventions
Python, known for its simplicity and readability, places a strong emphasis on writing clean and maintainable code. One of the key aspects contributing to this readability is adhering to Python Naming Conventions. In this article, we'll delve into the specifics of Python Naming Conventions, covering
4 min read
Python List Comprehension with Slicing
Python's list comprehension and slicing are powerful tools for handling and manipulating lists. When combined, they offer a concise and efficient way to create sublists and filter elements. This article explores how to use list comprehension with slicing including practical examples. The syntax for
3 min read
Python - Itertools.compress()
Pythonâs Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Co
2 min read
Python List Comprehension Interview Questions
List Comprehensions provide a concise way to create and manipulate lists. It allows you to generate a new list by applying an expression to each item in an existing iterable (e.g., a list, tuple, or range). This article covers a key list of comprehension interview questions with examples and explana
7 min read