Lists - Lakelands Computing

Title
Go to content
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
01234567
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:])

All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content