-2

In the case of this function starting from -2 position, it should print [115,43].

def increment(nums):


    t = (nums[-2:-4:-2 ])
    print(t)

    print(increment([43, 90, 115, 500]))  

However, the output for this code is just [115], how come?

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
Chris
  • 17
  • 4

2 Answers2

0

If you use [-2:-4:-1], you can see that the result is [115, 90] and 43 is not included. That's because python ranges are exclusive of the second bound.

If you want to include 43, you should use [-2:-5:-2]. Then the result would be [115, 43]

Amin
  • 2,605
  • 2
  • 7
  • 15
0

Try this code,

def increment(nums):
    print(nums[-2:-5:-2]) # output: [115, 43]

increment([43, 90, 115, 500])

slicing in python: slice(start, end, step)

when you give nums[-2:-4:-2 ] python will start from 115 and jumps 2 positions to the left and reach at 43 but you have set the end as 90 (-4 will go upto -3 position, not 43)

So, I just changed the end index to -5

Ajay
  • 53
  • 8