0

Say I have a list [0.67045, 0.662866] and I want to expand it to be, say size 8 and repeats until the size is reached;

[0.67045, 0.662866,0.67045, 0.662866, 0.67045, 0.662866,0.67045, 0.662866]

and if I give it a list of size 4; [0.850009, 0.439764, 0.849811, 0.440243] it will become

[0.850009, 0.439764, 0.849811, 0.440243, 0.850009, 0.439764, 0.849811, 0.440243]

and a list of size 8 simply wouldn't be expanded as it is equal to the size I want it to be.

How is this done in python?

Chase Allen
  • 33
  • 1
  • 7
  • It's an easy list appending, if you have done your search on google, you should be able to do this easily. What have you tried and where are you stuck at? – TYZ May 14 '20 at 02:15
  • Does this answer your question? [replicating elements in list](https://stackoverflow.com/questions/20276138/replicating-elements-in-list) – DarrylG May 14 '20 at 02:20
  • Well its a 2D array with 5 lists within it with each one doubling in length from the last; 'len(list[0]) = 2' , 'len(list[1]) = 4' , 'len(list[2]) = 8' , 'len(list[3]) = 16' , 'len(list[4]) = 32' , 'len(list[5]) = 64' , however I wish to expand each sub list to be of size 64 by simply repeating the preexisting values until that size is reached. I've thought of using nested for loops but I get lost and confused quite quickly as these operations will performed within this 2D list... – Chase Allen May 14 '20 at 02:22

2 Answers2

1

An easy way to do this without loops is to duplicate elements until you can be sure you have enough, then trim off the excess.

wanted_size = 11
arr = ['a', 'b']
result = arr * ceil(wanted_size / len(arr))  # expand to at least the wanted size
result = result[:wanted_size]  # trim off the modulus
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
-1

not memory effiecient but easy.

arr = [123,321]
cap = 8
(arr * cap)[:cap]
  • 2
    Please put your answer always in context instead of just pasting code. See [here](https://stackoverflow.com/help/how-to-answer) for more details. – gehbiszumeis May 14 '20 at 12:54