Python Comprehensions (Comprehensions)
Comprehensions are a very powerful and expressive syntactic sugar in Python, allowing you to create new lists, dictionaries, or sets from existing iterables (such as lists, tuples, sets, etc.) in a very concise way.
Using comprehensions not only makes code shorter and more readable, but is often faster than using traditional for loops.
List Comprehensions (List Comprehensions)
List comprehensions provide a compact syntax for creating lists.
Basic syntax:
[expression for item in iterable]
Example: Create a list containing squares of 0 to 9
Traditional for loop approach:
Using list comprehension:
List Comprehensions with Condition
You can add an if condition after the comprehension to filter elements.
Syntax:
[expression for item in iterable if condition]
Example: Create a list containing only squares of even numbers
List Comprehensions with if-else
You can also use if-else in the expression part to determine element values based on conditions.
Syntax:
[expression_if_true if condition else expression_if_false for item in iterable]
Example: Change odd numbers to negative, leave even numbers unchanged
Dictionary Comprehensions (Dictionary Comprehensions)
Similar to list comprehensions, dictionary comprehensions are used for quickly creating dictionaries.
Syntax:
{key_expression: value_expression for item in iterable}
Example: Create a dictionary of numbers and their squares
Example: Create a dictionary from a list
Set Comprehensions (Set Comprehensions)
The syntax for set comprehensions is almost identical to list comprehensions, but uses curly braces {}.
Syntax:
{expression for item in iterable}
Example: Create a unique set of squares from a list with duplicate elements
Comprehensions are an important part of Pythonic programming style. Mastering their use can significantly improve your coding efficiency and code quality.