Python Comprehensions
1. List Comprehension
Definition:
List comprehension is a concise way to create lists by applying an expression to each item in an existing iterable.
Syntax:
[expression for item in iterable if condition]
Example:
# List comprehension to create a list of squares squares = [x**2 for x in range(5)] # Square each number from 0 to 4 print(squares) # Output: [0, 1, 4, 9, 16]
2. Dictionary Comprehension
Definition:
Dictionary comprehension allows creating a dictionary from an iterable using a key-value pair.
Syntax:
{key_expression: value_expression for item in iterable if condition}
Example:
# Dictionary comprehension to create a dictionary with numbers and their squares squares_dict = {x: x**2 for x in range(5)} print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3. Set Comprehension
Definition:
Set comprehension is similar to list comprehension but creates a set. Sets automatically remove duplicate values.
Syntax:
{expression for item in iterable if condition}
Example:
# Set comprehension to create a set of squares squares_set = {x**2 for x in range(5)} print(squares_set) # Output: {0, 1, 4, 9, 16}
0 Comments