-1

The interval for N includes zero, so a trivial slicing lst[-n:] is not a solution here. I am looking for something like takeright from Scala.

Current solution:

lst = [1, 2, 3]
print(lst[len(lst) - n :])
dawid
  • 663
  • 6
  • 12
  • 2
    What does "N includes zero" mean? its unclear what you're asking, or why `lst[-n:]` isn't a solution – Sayse Jan 11 '20 at 19:10
  • 3
    @Sayse What they probably mean: if `n` is 0, they want an enpty list. `lst[-n:]` is in this case `lst[0:]`, which is a copy of the entire list. – glglgl Jan 11 '20 at 19:11
  • @glglgl - Fair enough. Possible duplicate: [Python negative zero slicing](https://stackoverflow.com/q/11337941/1324033) – Sayse Jan 11 '20 at 19:21

2 Answers2

3

According to your requirements, you only have to deal with the special case n == 0.

lst = [1, 2, 3]
print(lst[-n:] if n else [])

is probably the shortest resp. easiest you can have.

If you don't like that, you probably should stick with your solution.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

N includes zero, so a trivial slicing lst[-n:] is not a solution here.

If you want to handle the case when n is or less than 0, then you can use ternary operator in Python. Like this:

result = li[-n:] if n > 0 else []

Or

You can use your solution as mentioned in this answer too! (Thanks to @glglgl)

abhiarora
  • 9,743
  • 5
  • 32
  • 57