In this section, we will learn how to access the elements of a List in Python.
Note: we’re assuming you’re familiar with the Python List in General.
Python find Element in List
As mentioned in the Python List section, each element in a list has its own index number. For example, the first element is in the index number 0, the second element has the index number 1 and so on.
Now by using the name of a List (The variable that is pointing to the target list) + a pair of brackets on the right side of the list name and finally the index number of the target element as the argument to the pair of bracket, we can access the target element in order to either retrieve its value or replace it with a new one.
Access List Syntax:
listName[indexNumber] = value listNaem[indexNumber]
The first syntax is when we want to access a specific index of a list and replace the value with a new one.
The second syntax is used in other places where we only want to retrieve the value of a list at a specific index number.
Access List Example
list1 = ["Omid","Jack","Elon",True] list1 = "John" print(list1) print(list1)
Python List: Negative Indexing
We can use negative numbers as the index number as well! In such case, the value -1 points to the last element of the target list, the value -2 points to the element before the last element of the list and so on.
Example: using negative index number to access elements in python list
list1 = ["Omid","Jack","Elon",True] if list1[-1] == list1[len(list1)-1]: print("The two index numbers are pointing to the same value in the list")
The two index numbers are pointing to the same value in the list
Python List Slice
The Python list slice is explained in the next section.