Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
Example:
Positive indexing (from left side index starts from 0(zero))
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
c |
o |
m |
p |
u |
t |
e |
r |
-8 |
-7 |
-6 |
-5 |
-4 |
-3 |
-2 |
-1 |
Negative indexing (from right side index starts from -1)
n1=[‘c’ , ‘o’ , ‘m’ , ‘p’ , ‘u’ , ‘t’ , ‘e’ , ‘r’]
print(n1)
print(n1[-1])
print(n1[-2])
print(n1[-4])
output:
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
r
e
u
n1=['c','o','m','p','u','t','e','r'] print(n1) print(n1[-1]) print(n1[-2]) print(n1[-4]) print(n1[-5]) print(n1[-7])
Output:
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
r
e
u
p
o
Example:
n2=[‘c’ , ‘a’ , ‘t’ , ‘a’ , ‘l’ , ‘y’ , ‘s’ , ‘t’]
Positive indexing (from left side index starts from 0(zero))
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
c |
a |
t |
a |
l |
y |
s |
t |
-8 |
-7 |
-6 |
-5 |
-4 |
-3 |
-2 |
-1 |
Negative indexing (from right side index starts from -1)
n2=[‘c’ , ‘a’ , ‘t’ , ‘a’ , ‘l’ , ‘y’ , ‘s’ , ‘t’]
print(n2)
print(n2[-0]) # -0 is 0
print(n2[-2])
print(n2[-5])
print(n2[-7])
print(n2[-1])
print(n2[1])
print(n2[4])
print(n2[6])
output:
[‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’]
c
s
a
a
t
n2=['c','a','t','a','l','y','s','t'] print(n2) print(n2[-0]) # -0 is 0 print(n2[-2]) print(n2[-5]) print(n2[-7]) print(n2[-1]) print(n2[1]) print(n2[4]) print(n2[6])
Output:
[‘c’, ‘a’, ‘t’, ‘a’, ‘l’, ‘y’, ‘s’, ‘t’]
c
s
a
a
t
a
l
s
How to change/modify elements to a list?
List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.
n=[1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]
Positive index from left to right (starts from 0)
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
print(n)
n[0]=10
print(n)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[10, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
n=[1,2,3,4,5,6,7,8,9,10]
print(n)
n[2]=300
n[6]=200
n[8]=80
print(n)
output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 300, 4, 5, 6, 200, 8, 80, 10]
n=[1,2,3,4,5,6,7,8,9,10] print(n) n[2]=300 n[6]=200 n[8]=80 print(n)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 300, 4, 5, 6, 200, 8, 80, 10]
n=[10,20,30,40,50] print(n) n[2]=3000 n[3]=1200 n[3]=180 print(n)
Output:
[10, 20, 30, 40, 50]
[10, 20, 3000, 180, 50]