Lists
Lists (or arrays as they are often called) allow you to store multiple pieces of information at once. Each entry in a list is made up of a number showing the index (position) in the list and the piece of information - the value. You might also hear the term element instead of value.
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
value | "cat" | "dog" | "fish" | "bird" | "hamster" | "gerbil" | "lizard" | "snake" |
This list of pets shows how the index numbers work - note they start from 0. It is exactly the same as it was for characters in a string. In Python we would write this as:
- pets = ["cat","dog","fish","bird","hamster","gerbil","lizard","snake"]
A couple of things to draw your attention to here...
- Lists are defined by = [ ]
- You don't write the index numbers, they are automatically worked out
- Each item is separated by a , (a comma)
- Strings need to have their quotation marks " " otherwise Python will think they are variables
You can print out a list using print(pets) or whatever your list is called.
You can print one item from a list by using its position number like so:
- print(pets[0])
- print (pets[3])
The first one prints "cat" and the second one "bird"
You can also print sections of the list using the colon : either to separate the start and end of the section, or to say from first value to this index or from this index to the end (third and fourth examples). Run them in the trinket to see their exact output.
- print (pets[0:3])
- print (pets[2:5])
- print (pets[:4])
- print (pets[1:])