How can you return a sub list from a list returning 3 consecutive elements where the last element links back to the first given any index into the list?
For example, given index 3 for list = [1,2,3,4,5], would return [4,5,1]. Or given index 4 with list = [1,2,3,4,5], would return [5,1,2].
Options I have:
1. return list[index:] + list[:index+3]
2. return list[index:index+3] + list[:len(list)-index]
3. return list[index+3:] + list[:len(list)-index]
4. return list[index:index+3] + list[:max(0 , -1*(len(list)-index-3))]
Typical use case for the modulo operator %:
lst = [1,2,3,4,5] # do not shadow built-in 'list'
i = 3
[lst[x % len(lst)] for x in range(i, i+3)]
# [4, 5, 1]
i = 4
[lst[x % len(lst)] for x in range(i, i+3)]
# [5, 1, 2]
From your given options, the last one (4.) is the one that yields the same results:
lst[i:i+3] + lst[:max(0 , -1*(len(lst)-i-3))]
This you can easily confirm by simply trying it out ;)
You could use cycle, from the documentation:
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy.
Code:
from itertools import cycle, islice
lst = [1, 2, 3, 4, 5]
def get(l, index, length=3):
return list(islice(cycle(l), index, index + length))
print(get(lst, 3))
print(get(lst, 4))
Output
[4, 5, 1]
[5, 1, 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With