Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Popular Modern Must-Know

Python Idioms
Y. Bulavin
List Comprehensions Ternary Operator
Dictionary Comprehensions Boolean Chaining
Walrus Operator (:=) Iterators and Generators
f-Strings Context Managers
Unpacking Sequences Decorators
List Comprehensions

Concisely building new lists based on existing ones.

E.g., [square for x in range(10)] creates a list of squares from 0 to 9.


Dictionary Comprehensions

Similar to list comprehensions, but build dictionaries.

E.g., {x: x*2 for x in range(5)} creates a dictionary {0: 0, 1: 2, 2: 4, ...}.


Walrus Operator (:=):

Assigns a value and uses it in the same expression.

E.g., (total := sum(data)) * 2 assigns the sum of data to total and then
doubles it.
f-Strings

Embed variables and expressions directly into formatted strings.

E.g., f"The answer is {result:.2f}" formats result to two decimal places.


Unpacking Sequences

Assign multiple values from a sequence to variables simultaneously.

E.g., a, b, c = (1, 2, 3) assigns 1 to a, 2 to b, and 3 to c.

Conditional expression with a concise syntax.

E.g., positive = "Yes" if x > 0 else "No" assigns "Yes" to positive if x is


positive, else "No".
Ternary Operator

Conditional expression with a concise syntax.

E.g., positive = "Yes" if x > 0 else "No" assigns "Yes" to positive if x is


positive, else "No".
Boolean Chaining

Combine conditional expressions with and or or for concise checks.

E.g., if age > 18 and name == "Alice": print("Welcome!") checks both age
and name.
Iterators and Generators

Efficiently work with large or infinite data without storing everything in


memory.

E.g., use itertools functions like map and filter for concise processing.
Context Managers

Simplify resource management like opening and closing files with with
statements.

E.g., with open("data.txt") as f: print(f.read()) automatically closes the


file.
Decorators

Modify functions without changing their source code.

E.g., use @cache to memoize the results of a function for faster


subsequent calls.

You might also like