Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return sub list from a list where the last element links back to the starting index into the list

Tags:

python

list

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))]
like image 689
van neilsen Avatar asked Nov 18 '25 02:11

van neilsen


2 Answers

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 ;)

like image 51
user2390182 Avatar answered Nov 20 '25 18:11

user2390182


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]
like image 27
Dani Mesejo Avatar answered Nov 20 '25 18:11

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!