-4

peace upon you guys i was starting to learn python using head first book and i came across this [::-1] in lists i know that when u dont include the "start" it equals to 0 by default and the "stop" equals the maximum index number in the list so if we said the max is 5 so this means [0:5:-1] and if u run this u will get the first index but if u run this [::-1] it gives u the list in reverse order why? isnt [::-1] == [0:5:-1] but it seems it equals this instead [-1:5:-1]! so why the step index here define the start index !?

book = "The Hitchhiker's Guide to the Galaxy"
booklist = list(book)
booklist = ['T', 'h', 'e', ' ', 'H', 'i', 't', 'c', 'h', 'h', 'i',
        'k', 'e', 'r', "'", 's', ' ', 'G', 'u', 'i', 'd', 'e',
        ' ', 't', 'o', ' ', 't', 'h', 'e', ' ', 'G', 'a', 'l',
        'a', 'x', 'y']
backwards = booklist[::-1]
print(''.join(backwards))

output >>> yxalaG eht ot ediuG s'rekihhctiH ehT

backwards = booklist[0::-1] print(''.join(backwards))

output >>> T

backwards = booklist[-1::-1]
print(''.join(backwards))

output >>> yxalaG eht ot ediuG s'rekihhctiH ehT

1 Answers1

1

Slicing operation requires some steps if you provide. It is like this [start:stop:step] so if you write [::-1]. By default the start,stop,step all are None. As we provided the step of -1, means we decrement the index. So we get the reverse of input data.

>>> d = 'Galaxy'
>>> d[None:None:None]
'Galaxy'
>>> d[None:None:-1]
'yxalaG'
>>> d[::-1]
'yxalaG'
ksai
  • 987
  • 6
  • 18