Making a list

So far we’ve talked about numbers, strings and Booleans where each variable just stores one thing at a time. What happens if we want to manage a shopping list, or a list of students in my class… and I want to be able to manage that entire list of things together? Python allows us to create lists!

Here are three lists:

primes = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
vowels = ["A", "E", "I", "O", "U"]
starwars = ["Luke", "Han", "Leah", "Obi-wan", "Yoda", "Rey", "Finn"]

The two key tips to making a list: Python knows it is a list because of the square brackets! Items in a list are separated by commas!

Try the following to work out how the various commands behave.

print( len( starwars ) )
print( starwars[0] )
print( starwars[1] )
print( starwars[2] )
print( starwars[-1] )
print( starwars )

After doing the above, can you guess what this will do?

starwars.append("Darth Vader")
print( len( starwars ))
print( starwars[-1] )
print( starwars )

We can also use the “in” comparison test we used for strings

print( "r2d2" in starwars )

What command would make that print True?

What would these do?

print( starwars[0:2] )
print( starwars[1:3] )
print( starwars[:3] )
print( starwars[3:] )

How will this behave?

print( starwars )

Other tricks that are useful when we have lists of numbers:

minimum = min(primes)
maximum = max(primes)
print("The minimum was ",minimum," and the maximum was ",maximum)