Indexing

To get values from a list, you use indexing.

To index a list, you use square brackets ([]) with a number (or numbers) in the brackets specifying which elements of the list you want.

Let’s start with a list of fruit:

# command Python to make a list and store it fruit
fruit = ['apple', 'banana', 'grape', 'mango']

# command Python to get the length of your list
len(fruit)
4

Let’s try getting the first element in the list:

# command Python to print one element of your list
print(fruit[1])
banana

Is this what you expected? If not, you’re not alone. The trick is that Python starts counting at zero!

Here’s how you actually print the first element of the list:

# command Python to print the first element of your list
print(fruit[0])
apple

How do you think we can print the element mango in the list?

# command Python to print the element mango (2 ways)
print(fruit[3])
print(fruit[-1])
mango
mango

We can also get more than one element of a list:

# command Python to get the first 3 elements of the list and save it to fruit_subset
fruit_subset = fruit[0:3]

# command Python to print the length of fruit_subset
print(len(fruit_subset))
3
# command Python to print fruit_subset
print(fruit_subset)
['apple', 'banana', 'grape']

Note that in Python, the first number in indexing is inclusive and the second number is exclusive. In other words, you get the element corresponding to the first number (0), but not the element corresponding to the last number (3). This is like [0,3) in math.

Let’s print the second and third elements of the list:

# command Python to get the 2nd and 3rd elements of the list
print(fruit[1:3])
['banana', 'grape']

Now let’s get the second and fourth elment from the list:

# command Python to print the second and fourth elements from the list
print([fruit[1],fruit[3]])
['banana', 'mango']

You can also get letters in a string by indexing!

# command Python to store the first element of fruit (apple) in the variable a
a = fruit[0]
# command Python to print the first 3 letters in apple
print(a[0:3])
app

You just learned how to: * Get an element from a list or string * Get multiple elements from a list or string

Now it’s time to practice what you learned!