We are interviewing candidates for a job. We will call each candidate in order, represented by a Python list:
calls = ["Juan", "Zofia", "Amare", "Ezio", "Ananya"]
First, we’ll call
In Python, we call the location 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 the 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. If we wanted to select the third element from the list, we’d use
Note: When accessing elements of an list, 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 4th employee from the list
employees. Save it to the variable
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 an index that exists so that you don’t get an
Run your code again!