Python Tutorial | Python List

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.

n1=[‘c’ , ‘o’ , ‘m’ , ‘p’ , ‘u’ , ‘t’ , ‘e’ , ‘r’]

Positive indexing

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

n1=[‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]
print(n1)
#output:
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
print(n1[-1])
#output:
r
print(n1[-2])
#output:
e
print(n1[-4])
#output:
u

Example:

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
>>>

Example:

n2=[‘c’ , ‘a’ , ‘t’ , ‘a’ , ‘l’ , ‘y’ , ‘s’ , ‘t’]

Positive indexing

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

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 slice lists in Python?

In list We can access a range of items by using the slicing operator “:” (colon).

print(n1[1:3])
#counting starts from 0
#will display elements from start to position -1

Example:

n1=[‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]

Positive Indexing

0

1

2

3

4

5

6

7

c

o

m

P

u

t

e

R

n1=[‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]
print(n1)
#output:
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

print(n1[1:3])
#output:
[‘o’, ‘m’]

print(n1[1:4])
#output:
[‘o’, ‘m’, ‘p’]

print(n1[1:5])
#output:
[‘o’, ‘m’, ‘p’, ‘u’]

print(n1[2:3])
#output:
[‘m’]

print(n1[2:4])
#output:
[‘m’, ‘p’]

print(n1[2:5])
#output:
[‘m’, ‘p’, ‘u’]

n1=['c','o','m','p','u','t','e','r']
print(n1)
print(n1[1:3])
print(n1[1:4])
print(n1[1:5])
print(n1[2:3])
print(n1[2:4])
print(n1[2:5])

Output:

[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
[‘o’, ‘m’]
[‘o’, ‘m’, ‘p’]
[‘o’, ‘m’, ‘p’, ‘u’]
[‘m’]
[‘m’, ‘p’]
[‘m’, ‘p’, ‘u’]
>>>

Example:

n1=[‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’]

0 1 2 3 4 5 6 7
c o m p u t e r

0

1

2

3

4

5

6

7

c

o

m

p

u

t

e

r

print(n1)
#output
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]

print(n1[:0])
#output
[]

print(n1[:1])
#output (Only position 0 with be displayed i.e. : 0 to 1-1)
[‘c’]

print(n1[:2])
Output: (only elements of position 0 to 2-1 will be displayed)
[‘c’, ‘o’]

print(n1[:3])
#output:
[‘c’, ‘o’, ‘m’]

print(n1[:4])
#output:
[‘c’, ‘o’, ‘m’, ‘p’]

print(n1[:5])
#output:
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’]

n1=['c','o','m','p','u','t','e','r']
print(n1)
print(n1[:0])
print(n1[:1])
print(n1[:2])
print(n1[:3])
print(n1[:4])
print(n1[:5])

Output:

[‘c’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
[]
[‘c’]
[‘c’, ‘o’]
[‘c’, ‘o’, ‘m’]
[‘c’, ‘o’, ‘m’, ‘p’]
[‘c’, ‘o’, ‘m’, ‘p’, ‘u’]
>>>