1

I was wondering if there's a one line solution to print out a range from a potential negative index to a positive.

For example:

a = [1,2,3,4,5,6,7,8]
x1 = 2
x2 = 5
print(a[x1:x2])  # [3, 4, 5]

If x1 is negative, I want it to go from the negative index to whatever x2 is. So if x1 = -2 the result should be: [7, 8, 1, 2, 3, 4, 5]

However, currently this will return an empty list.

I could solve this by

x1 = -2
if x1 < 0:
   x = a[x1:] + a[:x2]
   print(x) #[7, 8, 1, 2, 3, 4, 5]

But I was wondering if there is a one line solution to this?

Tom
  • 1,979
  • 1
  • 21
  • 54

2 Answers2

3

Use a conditional expression:

print( a[x1:x2] if x1>=0 else (a[x1:]+a[:x2]) )
Scott Hunter
  • 44,196
  • 8
  • 51
  • 88
1

Using if statements are unavoidable here, but you can turn your code into a 1-liner using the python equivalent of the ternary operator.

>>> a = [1,2,3,4,5,6,7,8]
>>>
>>> def list_slice(list_, start, stop):
...     return list_[start:stop] if start >= 0 else list_[start:] + list_[:stop]
>>>
>>> list_slice(a, 2, 5)
[3, 4, 5]
>>> list_slice(a, -2, 5)
[7, 8, 1, 2, 3, 4, 5]
Lord Elrond
  • 9,016
  • 3
  • 20
  • 50
  • sorry I made a mistake in my code (updated it), I wanted to go from index -2 to index 5, so [7,8,1,2,3,4,5] – Tom Sep 28 '19 at 02:42