List

  1. Create list

    1
    2
    3
    a = [0, 1, 2]
    a.append(3) # a = [0, 1, 2, 3]
    a += [4] # a = [0, 1, 2, 3, 4]
  2. List index

1
2
3
for num,freq in collections.Counter(nums).items():
print("num ", num, ", freq ", freq)
buckets[-freq].append(num)
  1. Sort
    1
    intervals.sort(key=lambda x: x[0])
  • Random

    1
    random.random()
  • extend vs append
    We see that extend is semantically clearer, and that it can run much faster than append, when you intend to append each element in an iterable to a list.

    If you only have a single element (not in an iterable) to add to the list, use append.

1
2
3
4
5
6
import timeit

>>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz")))
2.867846965789795
>>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz")))
0.8060121536254883

https://stackoverflow.com/a/28119966/5133816