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

The output should be = [5, 3, 1]
But the real output is = [6, 4, 2] It seems like there is an invisible element after 6
Can anybody tell me why is that happened?

and I know if you leave the start index so it should be the first index of the list which is 0 (by default)
and if you leave the end index so it should be the last index of the list (by default) which is 5 in this case
so it means :
print(x[::-2]) should be the same as print(x[0:5:-2]) but when i try it

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

output = [] => an empty list why ???

mjokar
  • 1
  • 1
  • Why do you think it should be `[5, 3, 1]`? `[::-2]` is equivalent to `[len(X)-1:-1:-2]`. It starts at the last element, then goes down in increments of 2. – Barmar Oct 24 '22 at 22:58
  • 1
    The implicit start and stop reverse when using a negative slice; it's not the first and last index respectively anymore. – ShadowRanger Oct 24 '22 at 22:59
  • "It seems like there is an invisible element after 6" I don't understand why you think so. The slice `[::-2]` starts with the last element of the list, and takes every other element. The last element of the list is `6`. – Karl Knechtel Oct 24 '22 at 22:59
  • @Barmar: It's not actually equivalent to `[len(X)-1:-1:-2]` unfortunately (unlike a similar `range` definition), because `-1` means "the last element" (same as `len(X)-1` actually). There's no reasonable way to express the equivalence (the empty end is the same as `None` which means "continue until the beginning"). – ShadowRanger Oct 24 '22 at 23:02

0 Answers0