How to Access List Elements in Python
To access list elements in Python, you can follow three different methods.
The following examples show how to access list elements in Python.
Accessing Elements by Index
We can use the index to access elements in a list.
Suppose we have the following list:
# Declare list
data = ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma', 'Anita']
# Accessing the element using index
print("Accessed element:", data[0])
Output: 👇️
Accessed element: Anita
In this example, we use the index 0
to access the first element of the list.
Accessing Elements by Negative Index
We can use a negative index to access elements from the end of the list.
Suppose we have the same list as above.
We can use the following code to access the third-to-last element:
# Accessing the element using negative index
print("Accessed element:", data[-3])
Output: 👇️
Accessed element: Namita
In this example, we use the negative index -3
to access the third-to-last element of the list. The negative indexing starts from the last element in the list.
Accessing a Range of Elements Using Slicing
We can use slicing to access a range of elements in a list.
Suppose we have the same list as above.
We can use the following code to access the second and third elements:
# Accessing the second and third elements of the list
print(data[1:3])
Output: 👇️
['Sanika', 'Shubham']
In this example, we use slicing to access elements from index 1
to 2
(the end index 3
is not included).