List Comprehensions
- List comprehensions are a concise and efficient way to create lists in Python.
- They allow you to generate a new list by applying an expression to each item in an existing iterable (e.g., list, tuple, string) and filtering the items based on a condition.
- The syntax of a list comprehension is:
[expression for item in iterable if condition]
Example:
Dictionary Comprehensions
- Dictionary comprehensions allow you to create dictionaries in a concise manner.
- Similar to list comprehensions, they generate a new dictionary by applying an expression to each item in an iterable and filtering items based on a condition.
- The syntax of a dictionary comprehension is:
{key_expression: value_expression for item in iterable if condition}
Example:
Set Comprehensions
- Set comprehensions allow you to create sets in a similar way to list comprehensions and dictionary comprehensions.
- They generate a new set by applying an expression to each item in an iterable and filtering items based on a condition.
- The syntax of a set comprehension is:
{expression for item in iterable if condition}
Example:
Comprehensions in Python provide a concise and readable way to create lists, dictionaries, and sets based on existing iterables, making your code more elegant and efficient.