Lecture 9 - Lists

Lecture Date: Monday, February 8

We pick up today with the data types that can hold other data types. Specifically, lists. Tons to get through today! Let’s look at the code and learn as we go!

makinglists.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Mark Sherriff (mss2x)

animals = ['cow', 'horse', 'sheep', 'dog', 'chicken', 'llama'] # make a new list!

print(animals) # you can print the list

print(animals[0]) # you can get particular items from the list using []
print(animals[1])
print(animals[0] == 'cow') # == checks to see if two things contain the same data
print(animals[0] is 'cow') # is checks to see if two things are actually the same thing (more later)
print(animals[-1]) # negative numbers start from the end of the list
print(animals[-2])

print('The ' + animals[0] + ' and the ' + animals[2] + ' sleep in the barn.') # concat also works!

list_of_lists = [['cow', 'horse'], [4, 5, 6, 7]] # You can have a list of lists!

print(list_of_lists[0]) # here's how you get a particular list
print(list_of_lists[0][1]) # here's how you get a particular item
print(animals[2:4]) # this is called a slice and returns part of a list
print(type(animals[2:4]))
print(animals[0:-1])
print(animals[3:]) # you can shortcut some of the numbers here
print(animals[:3])
print(len(animals)) # len tells you how many things are in a list
print(len(list_of_lists))
print(len(list_of_lists[1]))

letters = ['A', 'B', 'C']
numbers = [1 , 2, 3]
both = letters + numbers # you can concatenate lists together, even if they have different things in them!
print(both)
print(letters * 3) # you can also repeat lists!
del animals[3] # if you know the index, you can delete a particular item
print(animals)

print('cow' in animals) # in checks for whether something is in an list
print('dog' not in animals) # or is not in a list
print(animals.index('sheep')) # lists have methods to get the index...
animals.append('duck') # ... append ...
animals.insert(3,'pig') # ... insert ...
print(animals)
animals.remove('duck') # note this can use the item and not the index like del
print(animals)
animals.sort() # and sort!
print(animals)
animals2 = animals
animals2.append('goat')
print(animals) # note same as animals2 - points to same place in memory!

import copy # making copies can be hard...
animals3 = copy.copy(animals)
animals3.append('farmer')
print(animals3)
print(animals)

# Reading in a list of numbers from the user

names = []
names.append(input("Give me a name: "))
names.append(input("Give me another name: "))
print(names)

# max and min