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
2
3
4
5
chars = ['a', 'b', 'c', 'd']

for i in range(len(chars)):
value = chars[i]
print("{}:{}".format(i, value))

Better

1
2
3
4
chars = ['a', 'b', 'c', 'd']

for i, value in enumerate(chars):
print("{}:{}".format(i, value))

  • Need to iterate two lists in parallel.
1
2
3
4
5
6
7
chars = ['a', 'b', 'c', 'd']
numbers = [1, 2, 3, 4, 5]

for i in range(len(chars)):
char = chars[i]
num = numbers[i]
print("{} {}".format(char, num))

Better

1
2
3
4
5
chars = ['a', 'b', 'c', 'd']
numbers = [1, 2, 3, 4, 5]

for char, num in zip(chars, numbers):
print("{} {}".format(char, num))

  • Avoid else blocks in for, while.

  • use list comprehension instead of map, filter

1
2
a = [1, 2, 3, 4, 5]
squares = map(lambda x: x**2, a)

Better

1
2
a = [1, 2, 3, 4, 5]
squares = [x**2 for x in a]
1
2
a = [1, 2, 3, 4, 5]
evens = filter(lambda x: x%2 == 0, a)

Better

1
2
a = [1, 2, 3, 4, 5]
evens = [x for x in a if x%2 == 0]
  • use generators if lists are large
1
[x for x in range(100000)]

Better

1
(x for x in range(100000))

Exception handling

1
2
3
4
5
6
7
8
try:
# Do something
except MyException as e:
# Handle exception
else:
# Runs when there are no exceptions
finally:
# Always runs