Lists (Arrays)

Definition

A list contains a number of items which are grouped together under one identifier. Each item in the list has a number associated with it. These index numbers start at zero.

Python doesn’t have arrays, so you will need to use lists.

Note

Lists can store different items with data types, but in general you should try to keep each item’s data types the same.

Easy example

colors = ['red', 'green', 'blue']

for color in colors:
   print(color)
Show/Hide Output
red
green
blue

Syntax

variableName = [item1, item2, item3, ...]

Examples

Example 1 - Creating an empty list

shoppingList = []

print(shoppingList)
Show/Hide Output
[]

Example 2 - Creating a list with items in

shoppingList = ['bread', 'milk', 'sugar']
print(shoppingList)
Show/Hide Output
['bread', 'milk', 'sugar']

Example 3 - Finding the length of a list

shoppingList = ['bread', 'milk', 'sugar']
print(len(shoppingList))
Show/Hide Output
3

Note

The length is 3. The item indexes are: 0, 1, 2.

Example 4 - Finding an item in a list

shoppingList = ['bread', 'milk', 'sugar']

print(shoppingList[1])
Show/Hide Output
milk

Note

The list starts at index 0 (zero), so shoppingList[1] is the second item in the list.

Example 5 - Updating an item in a list

shoppingList = ['bread', 'milk', 'sugar']

print(shoppingList)

shoppingList[1] = 'cream'

print(shoppingList)
Show/Hide Output
['bread', 'milk', 'sugar']
['bread', 'cream', 'sugar']

Example 6 - Sort a list

unsortedList = [3, 4, 2, 1, 5]

sortedList = sorted(unsortedList)

print(sortedList)
Show/Hide Output
[1, 2, 3, 4, 5]

Example 7 - Sort a list backwards

unsortedList = [3, 4, 2, 1, 5]

sortedList = sorted(unsortedList, reverse=True)

print(sortedList)
Show/Hide Output
[5, 4, 3, 2, 1]

Example 8 - Appending (adding) an item to a list

shoppingList = ['bread', 'milk', 'sugar']
shoppingList.append('jam')

print(shoppingList)
Show/Hide Output
['bread', 'milk', 'sugar', 'jam']

Example 9 - Removing an item from a list

shoppingList = ['bread', 'milk', 'sugar']

del shoppingList[1]

print(shoppingList)
Show/Hide Output
['bread', 'sugar']

Note

Remember that the list starts at index 0 (zero), so removing item 1 will be the second item in the list.

Example 10 - Seeing if an item is in a list

The following program will take a list of shopping items. For milk and jam it will print a customised message based on whether they are needed or not.

shoppingList = ['bread', 'milk', 'sugar']

if 'milk' in shoppingList:
    print('We need milk')
else:
    print('We don\'t need milk')

if 'jam' in shoppingList:
    print('We need jam')
else:
    print('We don\'t need jam')
Show/Hide Output
We need milk
We don't need jam

Example 11 - Looping through a list

shoppingList = ['bread', 'milk', 'sugar']

for item in shoppingList:
    print(item)
Show/Hide Output
bread
milk
sugar

Example 12 - Looping through a list (with range)

shoppingList = ['bread', 'milk', 'sugar']

for i in range(len(shoppingList)):
    print('Item ' + str(i) + ': ' + shoppingList[i])
Show/Hide Output
Item 0: bread
Item 1: milk
Item 2: sugar

Example 13 - Find the average of a list

scores = [72, 78, 83, 56, 89]

total = 0    #initial total which we add to

for score in scores:
    total = total + score
    print('current total: ' + str(total))

print('final total: ' + str(total))
Show/Hide Output
current total: 72
current total: 150
current total: 233
current total: 289
current total: 378
final total: 378

Example 14 - Building a 2D list

tictactoeBoard = [ ['-','-','-'], ['-', '-', '-'], ['-', '-', '-'] ]

print(tictactoeBoard)
Show/Hide Output
[['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]

Note

A 2D list (similar to a 2D array) is a list which contains lists. You can think of it as a table.

Example 15 - Accessing and updating an item in a 2D list

tictactoeBoard = [ ['-','-','-'], ['-', '-', '-'], ['-', '-', '-'] ]

tictactoeBoard[1][1] = 'x'
tictactoeBoard[1][2] = '0'

for row in tictactoeBoard:
    print(row)
Show/Hide Output
[['-', '-', '-'], ['-', 'x', '0'], ['-', '-', '-']]

Example 16 - Looping through a 2D list

testScores = [ [53,56,52,53], [82,83,91,87], [63,65,66,62] ]

total = 0
numberOfItems = 0

for scores in testScores:
    for individualScore in scores:
        total = total + individualScore
        numberOfItems = numberOfItems + 1

average = total / numberOfItems

print('Average score: ' + str(average))
Show/Hide Output
Average score: 67.75

Key points

Note

A 2D list can be used to form a simple table for a database. Each of the rows would be a record. Example 16 above, for instance, shows four test scores for three different students.

Note

While 2D lists can be used to make tables that store records for a simple database, in general we use SQL, which is far more powerful.