Accessing elements from the List
In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing.
Example 1: Accessing elements from list
# Python program to demonstrate
# accessing of element from list
# Creating a List with
# the use of multiple values
List = ["Geeks", "For", "Geeks"]
# accessing a element from the
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])
Output
Accessing a element from the list Geeks Geeks
Example 2: Accessing elements from a multi-dimensional list
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
# accessing an element from the
# Multi-Dimensional List using
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])
Output
Accessing a element from a Multi-Dimensional list For Geeks
Negative indexing
In Python, negative sequence indexes represent positions from the end of the List. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
# accessing an element using
# negative indexing
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
Output
Accessing element using negative indexing Geeks For
Complexities for Accessing elements in a Lists:
Time Complexity: O(1)
Space Complexity: O(1)
Python Lists
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by commas.