0

I would like an explanation of what's happening when I do the following:

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

The output is [6, 5] but can someone explain to me why? I understand when I do something like [i:j] with i > j but here it's reversed. The :-1 means we reverse mylist?

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
MinatoDBO
  • 45
  • 1
  • 7
  • "The `:-1` means we reverse `mylist`?" Yes. Normally there's an implicit (hidden) `:1]` at the end: `[i:j:+1]`, which means you `+1` to `i` until you reach `j` and then you stop. You can change the third thing to `2` which will `+2` to `i` until it reaches `j`, or you can `-1` or `-2` or `-whatever` which means add `-1` to `i` until you reach `j`. `i` has be greater than `j` in that case. – Boris Verkhovskiy Dec 24 '20 at 17:57
  • Thanks Boris for your explaination – MinatoDBO Dec 24 '20 at 21:57

4 Answers4

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

Basically when slicing it goes like this [start,end,skip]

So you start from the 5th index and end in the 3rd index(Python doesn't read the 3rd index, it stops whenever it reads the 3rd index)

So in total, its this:

[6,5]

Then you put -1 which skips(Basically if you put -1, the list reverses)

So [6,5] turns into this [5,6]

Srishruthik Alle
  • 500
  • 3
  • 14
1

The index of mylist starts from 0 and at 5th index the value is six. It is given that 5:3 that means it's range is from that. And the step is - 1. Now the output will start from 5th index value, next 4th index value and it stops there and it will not print 3rd index

0

You are using slice notation. The form is begin:end:step.

In your example, you are saying:

Start at index 5. So the output will start with mylist[5] or 6

End at index 3. The end is not included in the output, so the end will be mylist[4] or 5

Step of -1. So the index will decrement by 1 for each step. If you didn't have this, your output would actually be empty.

aviso
  • 2,371
  • 1
  • 14
  • 15
0

mylist[5:3:-1]

Here you are trying to get a reversed slice list so you have specified -1. If you want an increased reverse step you can mention it accordingly.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b1 = a[2:7]
b1 -> [2, 3, 4, 5, 6]
b2 = a[2:7:2]
b2 -> [2,4,6]
c1 = a[7:2:-1]
c1 -> [7, 6, 5, 4, 3]
c2 = a[7:2:-2]
c2 -> [7, 5, 3]
Chaithanya Krishna
  • 1,406
  • 1
  • 8
  • 13