-1
a=[1,2,3,4,5,6,7,8,9]
print(a[8:-10:-2])

output i get [9, 7, 5, 3, 1]

can anyone explain the logic and breakdown of python code output. I m just a beginner. I asked bing ai and chat gpt for answer. According to them output should be empty list whereas according to replit, codechef and jdoodle output should be [9, 7, 5, 3, 1].

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 2
    _According to them output should be empty list_ - Well, that's wrong. And now you realize that AI cannot (yet) replace programmers – OneCricketeer May 13 '23 at 13:45

2 Answers2

1

When we slice a list with a[start:stop:step], the slicing will start from the start index and stop at the stop index (exclusive), taking every step element.

a[8:-10:-2] means starting from index 8 (inclusive), going up to index -10 (exclusive) in reverse order, and taking every second element.

Since we are slicing the list in reverse order, index -10 is actually equivalent to index 0 when counting from the end of the list. So the slice actually goes from index 8 to index 0 (exclusive) in reverse order, taking every second element, which gives us [9, 7, 5, 3, 1].

hopefully this helps

Abdo
  • 31
  • 3
0

Your code translates to something equivalent to this:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
index = 8
result = []
while index > len(a) + -10:
    result.append(a[index])
    index += -2
print(result)

Make sure you identify your 8, -10, and -2 in there.

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38