In Python you can access an element from the list through the index number. To access an element you need to attach a square bracket and add the index number that needed to access.
In this article we will learn it by an example, so to begin with let’s create a cities name list.
citiesList = ["Paris", "Dubai", "Amsterdam", "Madrid", "Rome", "London", "Munich", "Berlin"]
In this list we have eight cities, each city has its own index number. The index number starts from zero (0). In this list, Paris’s index position is 0 and last item Berlin’s position is 7.
Access Element Through Index Number
In this list the first element is Paris, let’s access by index number.
print(citiesList) # Output: Paris
In this example, we attached square brackets to
citiesList along with 0 index that takes the first element from the cities list.
Similarly, if we replace zero index with 1 then output will be changed. Look at below example,
print(citiesList) # Output: Dubai
In the output of above example we got Dubai, it is because Dubai’s index position is 1 in the cities list.
Negative Index Number
Python allows access to an element from a list through a negative index number. In this case, python starts from the last element, for example in cities list Berlin’s position is -1. Below is an example.
print(citiesList[-1]) # Output: Berlin
In the above example, we got Berlin in the output for the -1 index number. Similarly, -2 will be returning the second last element and it will return onwards.