Tuesday 23 January 2024

Access list elements using negative indexing

In Python, it's possible to retrieve elements from the end of a list using negative indices. The last element is accessed with an index of -1, the second-to-last with -2, and so forth. This method is particularly useful for dealing with the last few elements of a list.

 


Let's apply this concept to the string 'Hello World'.

 

The string 'Hello World' has 11 characters, including the space:

 

a.   H (1st character, -11 in negative indexing)

b.   e (2nd character, -10 in negative indexing)

c.    l (3rd character, -9 in negative indexing)

d.   l (4th character, -8 in negative indexing)

e.   o (5th character, -7 in negative indexing)

f.     (space, 6th character, -6 in negative indexing)

g.   W (7th character, -5 in negative indexing)

h.   o (8th character, -4 in negative indexing)

i.     r (9th character, -3 in negative indexing)

j.     l (10th character, -2 in negative indexing)

k.    d (11th character, -1 in negative indexing)

 

If you want to access the character 'd' using negative indexing, you can use string[-1]. For the first 'l', you would use string[-8], and so on. Negative indexing is very handy in Python for accessing characters from the end of a string without needing to know the exact length of the string.

 

access_elements_using_negative_indexing.py

str = 'Hello World'

for i in range(-1, -12, -1):
    print(str[i], end='')

 

Output

dlroW olleH

 

Above snippet print the string from the end.

 

 


Previous                                                 Next                                                 Home

No comments:

Post a Comment