Lists
A list is a stored sequence of elements. They are ordered and may have members of different data types.
items = ["apple","pear",True,24]
print(items)
Lists can contain anything even other lists.
coords = [[0.4,255.3],[24.3,20.4],[-200.4,-95.3]]
Every item in a list has an index, starting from 0, so 0 would be the first item and the last
item would be the length of the list minus 1. We can get items from a list using their index, list[index]
.
cars = ["bently","bmw","audi","mercedes"]
car1 = cars[0]
car2 = cars[1]
last_car = cars[3]
The length of a list is the number of items in the list, we can use the len
function to get the
length of the list. For example, you may want to know how many customers you served in a day.
customers = [
"John",
"Bertram",
"Laufey",
"Rose",
"Jordyn",
"May"
]
print(len(customers))
If you try to get an index that isn't in the list python will raise an index of bounds error. caution
Common list operations
To add an item to the end of a list, we use the append
method.
members = ["Jack","David","Temi"]
members.append("Riri")
To remove the last item from the list, we use the pop
method.
colors = ["red","green","blue"]
blue = colors.pop()
green = colors.pop()
red = colors.pop()
Slicing
We can get a portion of the list using slices. The syntax for slicing is list[start:stop:step]
. start
indicates the index that the slice should start at, stop
indicates the index that
the slice should end, not including the last item and step
indicates how many steps to move forward.
Each of the parts (start
, stop
and step
) can each be omitted and the default value will be used.
colors = ["red","green","blue"]
slice = colors[0:2]
print(slice) # ["red", "green"]
This slice will start at index 0
and stop at index 2
, while not including the last index. If we wanted
to start at the second item and get the rest of the list we can start at index 1
and omit the stop
so
that the default value is used, which would be the length of the list.
colors = ["red","green","blue"]
slice = colors[1:]
print(slice) # ["green", "blue"]