# command Python to make a list and store it fruit
= ['apple', 'banana', 'grape', 'mango']
fruit
# command Python to get the length of your list
len(fruit)
4
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:
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:
How do you think we can print the element mango in the list?
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
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:
Now let’s get the second and fourth elment from the list:
['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!