1

new to python. Learn indexing and slicing. what does it mean.

for i in range (len(number)):
    if(number[-i-1]=='0'):

i don't understand this [-i-1]

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
Ros Al
  • 11
  • 1
  • 3
    The expression `-i -1` evaluates to a single number, given `i` is produced from `range`. The first iteration will have `i` as `0`, so it would result in accessing `number[-1]` when put together. This `for` loop looks to be accessing the list of `number` in reverse, as the subsequent iteration, it would be `-1 -1`, or `-2`. In any case, please refer to [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) as indexing is can be thought of as a subset of slicing in Python. – metatoaster Jul 02 '20 at 02:20
  • @metatoaster mmm or the other way around. `seq[whatever]` is *indexing*, if you pass a `slice` object as `whatever` that is a *slicing*. But I can see what you are saying. – juanpa.arrivillaga Jul 02 '20 at 02:30
  • Yeah, oops, I meant the other way around. Thanks for the correction. To recap, `slice` is basically a special type of index that can be passed to a list to return a segment of the list. – metatoaster Jul 02 '20 at 02:50

2 Answers2

1

the number I'm assuming is a list of numbers eg. [0,1,2,3,4]

the number[-i-1] refers to the number at the index of -i-1 (indexing)

for example when i = 0, -i-1 = -1, which in python means the last index or 1 from the back

which in my example would be 4

Slicing would be like numbers[2:4], which will return a portion of the array of [2,3]

1

What you are showing is indexing say your array is

number=[2,4,6,8,10]
number[0] is 2
number[-1] is 10

So, If you want to get the ith number from front the indexing is

number[i]

If you want to get the ith number from rear,which is your case then the indexing looks like

number[-i-1]

Just for your information slicing is used to get a part of the sequence in the array

number[1:4] gives [4,6,8] 
number[:4] gives [2,4,6,8]
number[4:] gives [10]

Hope this helps