Home > Back-end >  How can I append an item n times to a list?
How can I append an item n times to a list?

Time:01-23

I have a list of items to multiply by a second list of N items. How do I append to a new list so the index[i] of the first list is appended the corresponding index[i] number of times?

When I run the below code, it appends the elements but multiplies the string length, and does not append N times.

play_type = ['draw','sweep','counter','option','bootleg']
play_blend = [30,25,20,15,10]

play_master = []

for i in range(len(play_blend)):
    play_master.append(play_type[i]*play_blend[i])

CodePudding user response:

If you are trying to have one flat list of all items, you simply need a second loop. append will always append just one single item, whether it's an int or a list. It is also usually "cleaner" to use the zip function instead of iterating over indexes:

play_type = ['draw','sweep','counter','option','bootleg']
play_blend = [30,25,20,15,10]

play_master = []

for typ, blend in zip(play_type, play_blend):
    for _ in range(blend):
        play_master.append(typ)

Or, as a list-comprehension:

play_master = [typ for typ, blend in zip(play_type, play_blend) for _ in range(blend)]

You could, however, "save" one loop by using the extend method:

for typ, blend in zip(play_type, play_blend):
    play_master.extend([typ]*blend)

CodePudding user response:

An itertools version:

from itertools import chain, repeat

play_master = [*chain(*map(repeat, play_type, play_blend))]

Try it online!

CodePudding user response:

Try this:

play_type = ['draw','sweep','counter','option','bootleg']
play_blend = [30,25,20,15,10]

play_master = []
idx = 0
for i in play_blend:
    for m in range(i):
        play_master.append(play_type[idx])
    idx  = 1
print(play_master)

Output:

['draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw',
 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 
'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 'draw', 
'draw', 'draw', 'draw', 'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 
'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 
'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 'sweep', 
'sweep', 'sweep', 'sweep', 'sweep', 'counter', 'counter', 'counter', 
'counter', 'counter', 'counter', 'counter', 'counter', 'counter', 'counter',
 'counter', 'counter', 'counter', 'counter', 'counter', 'counter', 
'counter', 'counter', 'counter', 'counter', 'option', 'option', 'option', 
'option', 'option', 'option', 'option', 'option', 'option', 'option', 
'option', 'option', 'option', 'option', 'option', 'bootleg', 'bootleg',
 'bootleg', 'bootleg', 'bootleg', 'bootleg', 'bootleg', 'bootleg', 
'bootleg', 'bootleg']

If this is not the intended output please clarify.

  •  Tags:  
  • Related