2

What are the default values of start and stop in list slice? Do they change if the step is positive or negative?

For example:

 a = [1,2,3,4,5,6]
 print(a[::1]) 
 >>> [1, 2, 3, 4, 5, 6]

Above code makes it look that default value of start and stop are 0 and len(a).

But if we use a step = -1

 a = [1,2,3,4,5,6]
 print(a[::-1]) 
 >>> [5, 4, 3, 2, 1, 0]

Following python documenttation from https://docs.python.org/3/tutorial/introduction.html#strings

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

If that is the case we should get an empty list.

 a = [1,2,3,4,5,6]
 print(a[0:len(a):-1]) 
 >>> []

 a = "python"
 a[0:len(a):-1]
 >>>> ''
2ank3th
  • 2,948
  • 2
  • 21
  • 35

0 Answers0