2

I'm making a list in the following way:

lst = ['val1', 'val2', 'val3']

output = [item for it in lst]

...however, I would like to add an arbitrary number of each item to the list, not just one.

Something like this (if I wanted to add 3 elements each time to the list):

output = [item*3 for item in lst]

...so that if lst looks like this:

['val1', 'val2', 'val3']

...output looks like this:

['val1', 'val1', 'val1', 'val2', 'val2', 'val2'...]

How can I accomplish this?

marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
Warlax56
  • 1,170
  • 5
  • 30

2 Answers2

4

Like this (you'll have to change the code to suit your needs, obviously):

lst = ['val1', 'val2', 'val3']

output = [i for i in lst for x in range(3)]

print(output)

Output (formatted):

[
  'val1', 'val1', 'val1',
  'val2', 'val2', 'val2',
  'val3', 'val3', 'val3'
]

Change 3 to the number of times you want the item to repeat.

marsnebulasoup
  • 2,530
  • 2
  • 16
  • 37
2

How about just iterating through n x list?

li = ['val1', 'val2', 'val3']
n=3
print(sorted([el for el in li*n]))

Output:

['val1', 'val1', 'val1', 'val2', 'val2', 'val2', 'val3', 'val3', 'val3']
LevB
  • 925
  • 6
  • 10