Qaswed
Qaswed

Reputation: 3879

How to add a number to start and stop of a slice object in Python?

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?

Upvotes: 0

Views: 389

Answers (2)

Heike
Heike

Reputation: 24420

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']

Upvotes: 2

olinox14
olinox14

Reputation: 6653

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...

Upvotes: 0

Related Questions