Cheatography
https://cheatography.com
List of useful python features
This is a draft cheat sheet. It is a work in progress and is not finished yet.
Lists
Add or remove |
Append |
my_list.append(element)
|
Insert |
my_list.insert(index, element)
|
Remove by value |
my_list.remove(element)
|
Remove by index |
del my_list[index]
or my_list.pop(index)
|
Data Manipulation |
List comprehension |
[expression for item in list if condition]
|
Sorting |
|
Index of element |
my_list.index(element)
|
Count of element |
my_list.count(element)
|
Min/Max |
|
Concatenation |
|
List multiplication |
|
Conditional checks |
if all(logic)
or if any(logic)
|
Data Conversion |
List to string |
'separator'.join(my_list)
|
String to list |
string.split('separator')
|
Shallow copy |
|
Deep copy (requires import copy) |
copy.deepcopy(my_list)
|
Slicing |
Start, end, steps |
|
Reverse |
|
Negative starts (from end) |
|
Useful python
Writing files with open('filename.txt', 'w') as file: content = file.write()
|
Reading files with open('filename.txt', 'r') as file: content = file.read()
|
Checking type if isinstance(x, tuple):
|
Tuple unpacking x, y = tuple(1, 2,)
|
Timing import time class Timer: def __enter__(self): start_time = time.time() def __exit__(self, *args):end_time = time.time() print(f"{end_time - start_time} seconds") with Timer:
|
and vs or a = 1 b = 2 print(a or b)
returns a (first true or last false) print(a and b)
returns b (first false or last true) |
|
|
Dictionary (copy)
Add or remove |
Adding/Creating mydict['key'] = mydict['key'].get(v, default) + 1
|
Default dict (import defaultdict) defaultdict(default_type)
|
Adding/Updating my_dict['key3'] = 'value3'
|
Dictionary from two lists dict(zip(list_of_keys, list_of_values))
|
Remove del my_dict['key1']
or my_dict.pop('key2')
|
Accessing |
Accessing my_dict['key1']
or my_dict.get('key1', 'default_value')
|
Keys list list(my_dict.keys())
|
Values list list(my_dict.values())
|
Key: Value list list(my_dict.items())
|
Nested key/values my_dict['outer_key']['inner_key']
|
Safer nested dict my_dict.get('outer_key', {}).get('inner_key')
|
Filter {k: v for k, v in my_dict.items() if condition}
|
Functions |
Iterating for key, value in my_dict.items():
|
Looping with enumerate for index, (k, v) in enumerate(my_dict.items()):
|
Dict comprehension {k_expr: v_expr for item in iterable}
|
|
Sorting by key dict(sorted(my_dict.items()))
|
Sorting by value dict(sorted(my_dict.items(), k=lambda item: item[1]))
|
Copying |
Shallow copy new_dict = my_dict.copy()
|
Deep copy (import copy) new_dict = copy.deepcopy(my_dict)
|
|