Slicing
sequence[start:end:step]
- used to get SUB-sequence of string, list, tuple
- can also be used to create COPY of sequence
- can be used to REVERSE sequence using -1 step
Loops
- Need index and value of a list.
1 | chars = ['a', 'b', 'c', 'd'] |
Better
1 | chars = ['a', 'b', 'c', 'd'] |
- Need to iterate two lists in parallel.
1 | chars = ['a', 'b', 'c', 'd'] |
Better
1 | chars = ['a', 'b', 'c', 'd'] |
Avoid else blocks in for, while.
use list comprehension instead of map, filter
1 | a = [1, 2, 3, 4, 5] |
Better
1 | a = [1, 2, 3, 4, 5] |
1 | a = [1, 2, 3, 4, 5] |
Better
1 | a = [1, 2, 3, 4, 5] |
- use generators if lists are large
1 | [x for x in range(100000)] |
Better
1 | (x for x in range(100000)) |
Exception handling
1 | try: |