list.insert()¶We can use the function list.insert() in order to insert elements into a list. Consider the following list:
L = [42, 43, 45, 46, 47]
Suppose we want to insert 99 between 43 and 45. In order to do that, we use list.insert(). L.insert(ind, e) means "insert e before index ind in the list L"
L = [42, 43, 45, 46, 47]
L.insert(2, 99)
print(L)
We inserted 99 before 45, which used to be at index 4.
How can we insert an element at the beginning? Insert before index 0:
L = [42, 43, 45, 46, 47]
L.insert(0, 9)
print(L)
How about inserting an element at the very end? Technically, any large-enough index will work:
L = [42, 43, 45, 46, 47]
L.insert(10000000, 99)
print(L)
"Insert before index 10000000" just means "insert at the end" here. It's much nicer, however, to insert before index len(L). The index len(L)-1 is the index of the last element in the list (the indices are 0, 1, 2, 3..., len(L), for a total of len(L) indices). That means that inserting before index len(L) is the same as inserting the element at the very end:
L = [42, 43, 45, 46, 47]
L.insert(len(L), 99)
print(L)
list.append()¶"Inserting at the end of the list" has a name -- appending. We can (and should) use list.append to append to the end of a list.
L = [42, 43, 45, 46, 47]
L.append(99)
print(L)
list.index()¶Suppose we want to find the index of a particular element of L -- to find the location of the element equal to e in the list L. This can be done using list.index().
L = [4, 42, 35, 20]
L.index(20)
20 is found at index 3 of L. We can check this:
L[L.index(20)]
Of course, this would work for any element found in the list L, since L.index(e) is the index of an element equal to e!
L[L.index(4)]
What if the list L has more than one element that is equal to e? In that case, L.index(e) will return the smallest index of an element in L equal to e:
L = [4, 5, 7, 5, 20]
L.index(5)
What if the element is not found in L? In that case, we get an error, and the program crashes (unless we use exception handling, which we haven't covered...)
L.index(42)
in, not in¶We can use in and not in in order to check whether an element equal to e is in L or not.
e in L is True iff one of the elements of L is equal to e
e not in L is True iff none of the elements of L are equal to e
Of course, e not in L and not (e in L) are just the same.
Here are a few examples:
4 in [5, 6, 10]
3 in [10, 3, 1]
3 not in [10, 3, 1]
We are now in a position to try to find the index of an element which may or may not be present in L:
L = [10, 5, 4, 20, 4]
e = 3
if e in L:
print("The index of the first occurence of", e, "in L is", L.index(e))
else:
print(e, "is not in L")
L = [10, 5, 4, 20, 4]
e = 4
if e in L:
print("The index of the first occurence of", e, "in L is", L.index(e))
else:
print(e, "is not in L")