Python For GCSE
Lists In Python

In Python, lists are used to store multiple items using a single variable name. For the purposes of the GCSE examination, lists are the Python structure we use to practise working with arrays.

The following program defines two lists, one of strings, one of integers.

names = ["Andrew", "Barbara", "Charlie", "Dora"]

ages = [32, 43, 19, 52]

# the first name
print(names[0])

# the third age
print(ages[2])

In the example, notice how single items of the list can be accessed using a number. The first position in the list is numbered 0.

Note: Python does allow lists to contain items of different data types. This is not the behaviour you would expect from arrays in other programming languages. We will therefore only use lists with a single data type.

In this example, we use the len function to get the number of item in the list.

names = ["Andrew", "Barbara", "Charlie", "Dora"]

size = len(names)

print(size)

One of the most useful things about lists is that you can process them with loops.

names = ["Andrew", "Barbara", "Charlie", "Dora"]

ages = [32, 43, 19, 52]

for i in range(len(names)):
    print(names[i], ages[i])

Removing Items

names = ["Andrew", "Barbara", "Charlie", "Dora", "Enid", "Frank", "Gerry"]

# remove the last item
names.pop()
print(names)

# remove the item at position 2
names.pop(2)
print(names)


# remove the item equal to Frank
names.remove("Frank")
print(names)


# clear the list
names.clear()
print(names)

Adding Items

names = ["Andrew", "Barbara"]

# add to the end
names.append("Charlie")
print(names)

# insert at position 1
names.insert(1,"Me")
print(names)

# add another list to the end
names.extend(["A", "B", "C"])
print(names)