Editor settings

General settings

Save settings

Learn to program with Python

Accessing an element in a list #

We can access individual elements of a list using its index just like strings. The index starts at 0 for the first element and increases by 1 for each subsequent element. For example:

my_list = ['apple', 'banana', 'cherry']
print(my_list[0]) # Output: 'apple'
print(my_list[1]) # Output: 'banana'
print(my_list[2]) # Output: 'cherry'

We can also access elements of a list using the negative index, which starts at -1 for the last element and decreases by 1 for each preceding element. For example:

my_list = ['apple', 'banana', 'cherry']
print(my_list[-1]) # Output: 'cherry'
print(my_list[-2]) # Output: 'banana'
print(my_list[-3]) # Output: 'apple'

Exercise #

  • Create a new variable named fruit and assign the first element of my_fruits to it
  • Must use list index with [] to assign the value
Output will be displayed here