Junior — Middle
How is access to a specific element in a list by its index performed?
sobes.tech AI
Answer from AI
In Python, to access an element of a list by its position number, indexing with square brackets [] is used. Indexes start at 0, meaning the first element has index 0, the second — 1, and so on.
Example:
my_list = ['apple', 'banana', 'cherry']
# Get the first element
print(my_list[0]) # Outputs: apple
# Get the third element
print(my_list[2]) # Outputs: cherry
If you need to get an element from the end of the list, you can use negative indexes:
print(my_list[-1]) # Last element: cherry
print(my_list[-2]) # Second to last element: banana
It is important to remember that accessing an index outside the range of the list will raise an IndexError.