Accessing elements from the List
To access the list items, reference is made to the index number. Indexing in Python lists is handled in the same way as indexing strings. where the index starts from 0 . The first element of the list is stored at index 0, the second element of the list is stored at index 1, and so on.
Items in lists are accessed in two ways:
- Accessing list items by positive index number
- Accessing list items by negative index number
Accessing list items by positive index number
In the following example, we will define a variable named list that contains a list of integers.
Example:
# Example of accessing list elements by positive index number
list = [1,2,3,4,5]
print(list[1])
print(list[0:2])
print(list[1:5])
print(list[2:4])
The output will be:
2
[1, 2]
[2, 3, 4, 5]
[3, 4]
In the following example, we will define a variable named list that contains a list of texts. Then we display the value of the first and third element in it.
Example:
# Create a list using multiple values
List = ["Java", "Python", "C#"]
# Access an element fromundefined List using index number
print(List[0])
print(List[2])
The output will be:
java
C#
Accessing list items by negative index number
Negative indexing means starting from the end, -1 indicates the last element
In the following example, we will define a variable called list that contains a list of numbers.
Example:
# Example of accessing list elements by negative index number
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:-1])
The output will be:
5
[3, 4]
In the following example, we will define a variable named list that contains a list of texts. Then we display the value of the penultimate element and the last element.
Example:
# Create a list using multiple values
List = ["Java", "Python", "C#"]
# Access an item from the list using the index number
print(List[-1])
print(List[-2])
The output will be:
C#
Python
External sources:
List in Python - official Python documentation
If you have any questions or concerns, leave them in the comments
Tags
Python python data types python lists Accessing list elements
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment