Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat list if index range is out of bounds

Tags:

python

I have a Python list

a = [1, 2, 3, 4]

and I'd like to get a range of indices such that if I select the indices 0 through N, I'm getting (for N=10) the repeated

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]

I could of course repeat the list via (int(float(N) / len(a) - 0.5) + 1) * a first and select the range [0:10] out of that, but that feels rather clumsy.

Any hints?

like image 571
Nico Schlömer Avatar asked Nov 29 '25 03:11

Nico Schlömer


2 Answers

You can simply use the modulo operator when accessing the list, i.e.

a[i % len(a)]

This will give you the same result, but doesn't require to actually store the redundant elements.

like image 76
Sven Marnach Avatar answered Dec 01 '25 18:12

Sven Marnach


You can use itertools.cycle and itertools.islice:

from itertools import cycle, islice

my_list = list(islice(cycle(my_list), 10))

Note that if you just want to iterate over this once, you should avoid calling list and just iterate over the iterable, since this avoids allocating repeated elements.

like image 34
Bakuriu Avatar answered Dec 01 '25 16:12

Bakuriu



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!