0

The general syntax of slicing

[start:stop:step]

It will be evaluate start:stop-1 and step(default 1)

>>> l = [x for x in range(5)]
>>> l[0:6]
[0, 1, 2, 3, 4]
>>> l[1:-1] #case second
[1, 2, 3]
>>> l[1:-5] #case third
[]

Why in the case third it returns an empty list and also i don't understand in case second how step can be incremented by 1 if stop value in -ve.

Harrish Kumar
  • 116
  • 3
  • 10

1 Answers1

-1
l[-5] = 0

so doing:

l[1:-5]

is the same as doing:

l[1:0]

and like any other negative range (do not confuse with negative number!) - it will return an empty list

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • Ok, in this case as elements are consecutive integers staring from 0. Say `[x*2 for x in range(10)]` be the list. `l[-5]` is 10. `l[1:-5]` is not equal to `l[1:10]` and not an empty list as well. – Austin Jul 27 '19 at 09:01
  • @alfasin then why in _case second_ it returns an non-empty list. It will be same as `l[1:5]` i know that. I wanna to know how **step** will be incremented by **1** if **stop** is -ve and `range(1,-1)` returns an empty list. – Harrish Kumar Jul 27 '19 at 09:18
  • `and like any other negative range - it will return an empty list`, that's not true, eg. `l[1:-1]` will give you `[1, 2, 3]` which is same as `l[1:4]`, only cases where the negative index overshoots the positive index in it's representation so that stop <= start will it give an empty list e,g, `l[1,0]` or `l[1:1` – Devesh Kumar Singh Jul 27 '19 at 10:08
  • @HarrishKumar as you noted: `l[1:-1]` is the same as `l[1:4]` - this is _not_ negative range ;) – Nir Alfasi Jul 27 '19 at 10:09
  • @DeveshKumarSingh see my previous comment, in this case `l[1:-1]` is _not_ negative range (don't mistake negative integer with negative range). – Nir Alfasi Jul 27 '19 at 10:10
  • Guys, when you're using a negative _index_ it doesn't mean that what you're getting is necessarily a negative range: negative index `-i` translates into a positive index `len(l)-i` and this is the number that you should consider. `l[3:4]` is a positive range while `l[4:3]` is a negative range. If you write the `4` as `4` or as `-1` (when the length of the list is 5) is not the point. Hope this clarifies it. – Nir Alfasi Jul 27 '19 at 10:13
  • @alfasin from ur comment i'll understand that python will convert `l[1:-1]` into `l[1:4]` at backend. Do have references/links in support of your answer. – Harrish Kumar Jul 27 '19 at 11:33
  • 1
    @HarrishKumar https://www.pythoncentral.io/cutting-and-slicing-strings-in-python/ and https://docs.python.org/3/faq/programming.html?highlight=negative%20index#what-s-a-negative-index also http://knowledgehills.com/python/negative-indexing-slicing-stepping-comparing-lists.htm – Nir Alfasi Jul 27 '19 at 17:41