List
Mutable, ordered series, traditionally of the same type of object.
Advantages: Mutable and ordered. Easy to understand. Relatively efficient memory usage.
Disadvantages: Searching is O(n).
Creating a list use square brackets
mylist = [ ]
mylist = [1,2,3]
mylist = [1,2,3,"a"]
mylist = ['a', 'b', 'c', [1,2,3] ] # 4 elementsChecking membership
3 in mylist # True or False
# O(n) time complexity
mylist.index(3) # get the index of a elementConverting from another type
list('abc') # ['a','b','c']
list((1,2,3)) # [1,2,3]
list({1,2,3}) # [1,2,3]Slicing
A = [0, 1, 2, 3, 4, 5]
A[2:4] # [2, 3]
A[2: ] # [2, 3, 4, 5]
A[ :4] # [0, 1, 2, 3]
A[ :-1] # [0, 1, 2, 3, 4]
A[-3: ] # [3, 4, 5]
A[-3:-1] # [3, 4]
A[1:5:2] # [1, 3]
A[5:1:-2] # [5, 3]
# reverse a list
A[ : :-1] # [5, 4, 3, 2, 1, 0]
# rotate a list
A[3: ] + A[ :3] # [3, 4, 5, 0, 1, 2]
# shallow copy a list
B = A[:]Replacing an existing element
Replacing multiple existing elements
Adding an element to the end
Adding multiple elements to the end
Insert a element into a list at specific index
Removing an element from the end
Removing an element from any index
Removing an element based on its value (rather than its position)
Removing a slice
Sorting
Reversing
Joining strings with delimiter
Iterating over the elements
Iterating over the sorted elements
Computing the length of a list
Find max/min value in a list
Last updated