I want to build some lists (a, b, c, d) by extending periodically those given in input.
The structure of the periodicity is such that the first element of each list must not be repeated, while all the other elements must be until the maximum length set in input is reached (it is possible that the period does not get to be repeated an integer number of times).
To give an example, if I have as input
a = [1, 2, 3, 4] max_len=11
I want to obtain as output
a = [1, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2]
I wrote this piece of code:
for mylist in [a, b, c d]:
period = mylist[1:] # all elements but the first are repeated
while len(mylist)< max_len:
mylist.extend(period)
mylist = mylist[:max_len] # cut to max_len
print mylist
print a, b, c, d
If I run this, I see from the two print commands that my lists are how I want them to be while the program is still in the loop, but they get back to the “non-sliced” length when out of the loop, that is, a gets back to the length greater than max_len where the period is repeated exactly 4 times:
a = [1, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4]
Why is that? It looks like the program has forgotten the slicing (but not the extension).
I understand that it is a pretty simple problem, and I could get around it in some other way, but I would like to understand why this idea does not work.
Thank you for your help!
The problem is that
mylist = mylist[:max_len]creates a new list instead of modifyingmylistin place, so the results never propagate back toaet al.If you replace:
with
that’ll fix it.
As an aside, you could use
itertoolsfor the transformation: