Python
Data types and methods
list:
- zip
- enumerate
- reverse list: some_list[::-1]
dict: - get - setdefault
example
student_grades = {}
spanish_grades = student_grades.setdefault("Roberto", {})
spanish_grades["spanish"] = 90
print(student_grades) # {"Roberto": {"spanish": 90}}
for-else and while-else
nums = [1, 2, 3, 4, 5,]
find = 4
for num in nums:
if num == find:
print(f"found {find} in the list.")
break
else:
# This block will execute only if the loop completed without encountering a 'break'
print(f"{find} was not found in the list.")
count = 5
while count > 0:
print(count)
count -= 1
else:
# This block will execute once the condition in the while statement is no longer true
print("Liftoff!")
pretty printing
walrus operator
example
numbers = [2, 8, 0, 1, 1, 9, 7, 7]
description = {
"length": (num_length := len(numbers)),
"sum": (num_sum := sum(numbers)),
"mean": num_sum / num_length,
}
print(description) # {'length': 8, 'sum': 35, 'mean': 4.375}
comprehensions
list, dict, set, generator
e.g.
some_list = [a for a in b if some_condition]
Functional
lambda functions
anonymous functions
z = lambda x: x * 3
use lambda function to sort dictionary by specific key
people = [
{"name": "Oppenheimer", "age": 62},
{"name": "Einstein", "age": 76},
{"name": "Schubert", "age": 31},
]
people.sort(key=lambda person: person['age'])
map
filter
reduce
unknown number of function arguments
Swap values
Ternary / in-line if statement
Switch-case / structural pattern matching
OOP dunder methods
Decorators
e.g. the built-in @staticmethod
Generators
e.g. if you only need access to a few items at a time,
context managers
Metaclasses
Concurrency and parallellism
GIL.
multi-processing / multi-threading
Testing
TDD with Pytest