A list is a data structure, to store a collection of elements with dynamic size in nature.
Access elements of a list in Python
List elements are accessed by an index. The index can be a positive or negative number.
For example, if the list contains elements the size of 5, the Index is always in the range of -4 to 4. Other index values throw an error. the positive index always gets the elements from the begining of a list A negative index get the elements from the end of a list The index always starts with 0 for the first element, last element index is len(list)-1.
numbers=[1,3,5,7,9];
print(numbers[0]) # 1
print(numbers[4]) # 9
The above example list contains a size of 5. first element index is zero, last element index is 4.
If you access a list with an index greater than 4(index=5), It throws an IndexError: list index out of range
error.
print(numbers[5]) # 9
Output:
Traceback (most recent call last):
File "C:\Users\Kiran\PycharmProjects\myapp\arraytest.py", line 4, in <module>
print(numbers[5]) # 9
~~~~~~~^^^
IndexError: list index out of range
List with negative index example:
numbers=[1,3,5,7,9];
print(numbers[-1]) # 9
print(numbers[-4]) # 3
print(numbers[-5]) # IndexError: list index out of range
How to find the size of an array in Python
Array size is the count of elements in it. len(array) function returns an array length
numbers=[1,3,5,7,9];
print(len(numbers)) # 5
Array iterate elements using for in loop
numbers=[1,3,5,7,9];
for element in numbers:
print(element);