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
fruitand assign the first element ofmy_fruitsto it - Must use list index with
[]to assign the value
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules