0

I read this question about slicing to understand the slicing in Python a bit better, but found nothing about increasing the start and stop of a slice object by a constant in a simple way. By "simple" I mean: a) in the same line and b) in one place and c) without an extra variable.

['a', 'b', 'c', 'd', 'e'][0:2]         #works
['a', 'b', 'c', 'd', 'e'][(0:2)+1]     #does not work, what I would find most convenient
['a', 'b', 'c', 'd', 'e'][(0+1):(2+1)] #works, but needs a change at two places
i = 1
['a', 'b', 'c', 'd', 'e'][(0+i):(2+i)] #works but needs an extra line and variable

On the slice level, slice(0, 2, 1)+1 does not work since "unsupported operand type(s) for +: 'slice' and 'int'". So, how to add a number to start and stop arguments of a slice object in Python in a simple way?

Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • 3
    it looks like your final example does what you want, can you clarify your question – depperm May 16 '19 at 12:47
  • 3
    How you solve this problem depends on what the surrounding code does and looks like. Using a variable seems a good enough solution. – Diptangsu Goswami May 16 '19 at 12:50
  • @Qaswed Are you trying to ask how to get a fixed sized slice but be able to easily change where you are taking the slice from? Like you might want `arr[0:2]` or `arr[2:4]` or `arr[4:6]`. – Quinn Mortimer May 16 '19 at 12:57
  • @depperm I made clear what "simple" means to me, and thus why my final example is not "simple" in my sense and is not the desired solution for me. – Qaswed May 16 '19 at 12:58
  • @QuinnMortimer exactly – Qaswed May 16 '19 at 12:58

2 Answers2

2

To avoid writing +i twice you could do something like

my_list[i:][:length]

Example:

i = 2
length = 3
print(['0', '1', '2', '3', '4', '5', '6', '7'][i:][:length])

--> output: ['2', '3', '4']
Heike
  • 24,102
  • 2
  • 31
  • 45
0

There is no way to achieve such a thing. If you really want to do that with only one line, you still can do:

x=1; l[x:x+2]

But this is a little ugly...

olinox14
  • 6,177
  • 2
  • 22
  • 39