Lists

Initialization

list() # create an empty list
[] # create an empty list
list(set(1,2)) # [1, 2] create list from set
[1,2] # create a list with elements

Methods

[1].append(2) # [1, 2]
[1].extend([2]) | [1] + [2] # add 2 to [1]
[1].insert(0, 0) # [0, 1]
[1].remove(1) # [] remove first element equal to item.
[1,2,3].pop() # [1,2] remove last element
[1,2,3].pop(0) # [2,3] remove first element
[1].clear() # [] empty list
[1,1].count(1) # 2 return times item appears in list.
[3,4,2].sort() # [2,3,4] sort in place
[(2,3), (1,2)].sort(key=lambda x: x[1]) # [(1, 2), (2, 3)] sort with lambda
[1,2,3].sort(reverse=True) # [3,2,1] sort in reverse
[1,2,3].copy() # [1,2,3] return shallow copy of list
[1,2,3][:] # [1,2,3] return shallow copy
x = [1,2,3]
del x[0] # delete without popping
x # [2,3]

Iterating with index:

arr = [1,2,3]
for i, num in enumerate(arr):
    print(i, num) # (0, 1), (1, 2), (2, 3)

Comprehensions

Instead of:

squares = []
for x in range(3):
    squares.append(x**2)
squares # [1,4,9]
squares = [x ** 2 for x in range(1, 4)]

We can add flow control:

squares = [x ** 2 for x in range(1, 4) if x > 3] # [4, 9]