In [ ]:
some_list = [10,20,30]
print(some_list[2])
In [ ]:
some_list = [10,20,30]
print(some_list[0])
In [ ]:
some_list = [10,20,30]
print(some_list[-1])
In [ ]:
some_list = [10,20,30,40]
print(some_list[1:3])
In [ ]:
some_list = [10,20,30]
print(some_list[:3])
In [ ]:
some_list = [0,10,20,30,40,50,60,70]
print(some_list[2:4])
In [ ]:
some_list = [10,20,30]
some_list[0] = 50
print(some_list)
In [ ]:
some_list = []
for i in range(5):
some_list.append(i)
print(some_list)
In [ ]:
some_list = [1,2,3]
some_list.insert(2,5)
print(some_list)
In [ ]:
some_list = [10,20,30]
some_list.pop(1)
print(some_list)
In [ ]:
some_list = [10,20,30]
some_list.remove(30)
print(some_list)
In [ ]:
In [ ]:
# You can put anything in a list
some_list = ["test",1,1.52323,print]
In [ ]:
# You can even put a list in a list
some_list = [[1,2,3],[4,5,6],[7,8,9]] # a list of three lists!
In [ ]:
# You can get the length of a list with len(some_list)
some_list = [10,20,30]
print(len(some_list))
In [ ]:
some_list = [10,20,30]
another_list = some_list
some_list[0] = 50
print(some_list)
print(another_list)
In [ ]:
import copy
some_list = [10,20,30]
another_list = copy.deepcopy(some_list)
some_list[0] = 50
print(some_list)
print(another_list)
The previous cells demonstrate a common (and confusing) python gotcha when dealing with lists.
The statement
another_list = some_list
says that another_list is some_list. These are now two labels for the same underlying object. It does not create a new object. If I change some_list, it changes another_list because they are the same thing. In programming terms, another_list and some_list are both references to the same object.
I can write:
Mary is also known as Jane.
I can then use "Mary" or "Jane" and it will be understood both labels point to the same person. If I say, "Jane has red hair", it implies that "Mary" also has red hair because they are the same person.
In our Mary and Jane analogy, the sentence would be:
I cloned Mary and named the clone Jane.
Now the two labels point to to different people. If I say "Jane has red hair" it does not imply that "Mary has red hair" (Mary may have dyed her hair blue).
0 and count to N-1. -1) count from the right side.:" lets you slice lists. some_list[i:j+1] returns the $i^{th}$ through the $j^{th}$ entries in the list. some_list[:3] gives the $0^{th}$ through the $2^{nd}$ entries.some_list[1:-1] gives the $1^{st}$ through the last entries.some_list[:] gives the whole listsome_list[i] = xsome_list.append(x)some_list.insert(i,x)some_list.pop(i)some_list.remove(x)If you want to copy a list, do:
import copy
some_list = [1,2,3]
list_copy = copy.deepcopy(some_list)