Lists Quick Review
Lists = An ordered sequence of values where indexing starts at 0 (not 1!), which we can create using [ ] brackets
lst = [1, 2, 3]
lst => 1
lst => 2
lst => 3
lst => ERROR, since we only have 3 elements
List slicing = Creating a copy of a portion or all of a list. List slicing is formatted with [start index (inclusive): end index (exclusive): skip], though you can choose to omit any of them if you’re using their default values (for start index, the default is 0, for end index, the default is the last index of the list, and for skip, the default is 0).
lst2 = [4, 5, 6, 7, 8]
lst2[1 : 5 : 2] => [5, 7]
This slicing will take from element 1 inclusive to element 5 exclusive with a skip of 2, which is a fancy way of saying that we’re copying every other element of the list [5, 6, 7, 8].
List comprehension = A compact, one line for loop that returns a list. List comprehensions are always formatted with [expression for variable name in list name if condition], though you can choose to omit the condition if you want to use all of the elements in your list. Another important thing to note is that this does not change your original list at all; it is creating a brand new list.
lst3 = [9, 10, 11, 12]
[x + 1 for x in lst3 if x % 2 == 0] => [11, 13]
This list comprehension will go through all of the elements in lst3, and if an element is even, it will add 1 to the element and add it to the return list. And remember, lst3 will not be changed at all.
Important List Functions
range(a, b): Gives a list of numbers from a to b excluding b
len(lst): Gives the length of lst
lst.append(x): Adds element x onto the end of a lst and returns none -- if x is a list, the last element of lst becomes a pointer to list x
lst.extend(x): Adds a list onto the end of a list and returns none (in this case, x has to be a list, not just one element)
lst.pop(x): Removes and returns element at index x (or the last element if no index is specified)
lst.remove(x): Removes element x from lst (or does nothing if x is not in lst) and returns none