- Lists are essential when using Python to store large amounts of information, especially if we don’t know how much in advance
- A list has a name, just like a variable but there may be many lists within it too (known as two-dimensional lists (that’s for later!)
- Each list has an index, starting at 0
- The example below is known as a one-dimensional list
#Create a list containing 4 names
#Leave square brackets empty to create an empty list
names = ['Joe','Mike','Sarah','Charlie']
#Lists can also contain numbers
numbers = [23,45,6,9,10]
#Will print "Sarah"
print(names[2])
#Add to the end of the list
names.append("Alf")
#Remove a name from the list
names.remove("Mike")
#Remove by index number if known, no number pops last the list
names.pop(2)
#Find the length of the list (returns a numerical value)
list_length = len(names)
#Empty the list entirely
names.clear()
Tasks
- Type in the code and make sure that it works
- Add print statements at relevant points to show what effect each line has on the list
- Save and label your code
Extension Task
A while loop if frequently used to allow a user to keep adding new names to the list, until a specific character (such as ‘Q’) is detected, when it will stop and print out the list. Can you implement this technique?