Chris is interviewing candidates for a job. He will call each candidate in order, represented by a Python list:
calls = ['Ali', 'Bob', 'Cam', 'Doug', 'Ellie']
First, he’ll call
In Python, we call the order of an element in a list its index.
Python lists are zero-indexed. This means that the first element in a list has index
0, rather than
Here are the index numbers for that list:
In this example, the element with index
We can select a single element from a list by using square brackets (
) and the index of the list item. For example, if we wanted to select the third element from the list, we’d use
>>> print(calls) 'Cam'
Note that when accessing elements of an array, you must use an
int as the index. If you use a
float, you will get an error. This can be especially tricky when using division. For example
print(calls[4/2]) will result in an error, because
4/2 gets evaluated to the
To solve this problem, you can force the result of your division to be an
int by using the
int() takes a number and cuts off the decimal point. For example,
int(5.0) will both become
calls[int(4/2)] will result in the same value as
calls[4/2] will result in an error.
Use square brackets (
]) to select the element with index
4 from the list
employees. Save it to the variable
len to display how many items are in
Paste the following code into script.py:
What happens? Why?
Selecting an element that does not exist produces an
In the line of code that you pasted, change
8 to a different number so that you don’t get an