Accessing Elements

Accessing Elements

In Python, we can access elements of the list either by using index or by using slice operator (:).

1. By using Index
  • List follows zero based index. i.e., index of first element is zero.
  • List supports both +ve and -ve indexes.
  • +ve index meant for Left to Right
  • -ve index meant for Right to Left
  • list = [10, 20, 30, 40]
Python Lists
print(list[0]) ==> 10
print(list[-1]) ==> 40
print(list[10]) ==> IndexError: list index out of range
2. By using Slice Operator

Syntax

list2 = list1[start:stop:step]

Where

Start ==> It indicates the Index where slice has to Start. Default Value is 0

Stop ==> It indicates the Index where slice has to End Default Value is max allowed Index of List i.e., Length of the List.

Step ==> increment value Default Value is 1.

n=[1,2,3,4,5,6,7,8,9,10] 
print(n[2:7:2]) 
print(n[4::2]) 
print(n[3:7]) 
print(n[8:2:-2]) 
print(n[4:100])

Output

ashok@ashok:~$ py test.py
[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9, 10]
List vs Mutability

Once we creates a List object, we can modify its content. Hence List objects are mutable.

n=[10,20,30,40] 
print(n) 
n[1]=777 
print(n)
ashok@ashok:~$ py test.py
[10, 20, 30, 40]
[10, 777, 30, 40]
Accessing Elements
Scroll to top