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 :])
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 :])
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.
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)