slap-a-da-bias
slap-a-da-bias

Reputation: 406

cycle through a list while skipping elements (python)

I'm trying to find a way of going through a loop of a single list skipping the first element each time.

so for example, if I have a list:

lst = [0,1,2,3,4,5,6]

and wish to use a for loop to cycle through all but the first element and stop at an arbitrary point. So if I wish to start at index 1 of lst and advance through a cycle of each element (excluding the first) I can use the following:

scd = [1,2,3,4,5,6]
out = []
for i in range (1,14+1):
    if (i%len(lst)) not in scd:
        continue
    else:
        out.append(lst[i%len(lst)])
print(out)

it returns a list with only 12 elements:

[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]

The output that I'm trying to get is:

[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]

I know the issue is in using the continue in the for loop, but I'm struggling with a workaround that gets me the desired output.

Any help would be greatly appreciated. also if there's a more pythonic way of going about this problem, I'm all ears.

Thanks so much.

Upvotes: 0

Views: 92

Answers (1)

user7864386
user7864386

Reputation:

IIUC, you simply want to repeat the same list, right? How about this where you could concatenate lists using divmod:

num = 14
i,j = divmod(num, len(lst)-1)
out = lst[1:] * i + lst[1:1+j]

Output:

[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]

Upvotes: 2

Related Questions