1

I have a list of strings and want to get a new list consisting on each element a number of times.

lst = ['abc', '123']
n = 3

I can do that with a for loop:

res = []
for i in lst:
    res = res + [i]*n
print( res )

['abc', 'abc', 'abc', '123', '123', '123']

How do I do it with list comprehension?

My best try so far:

[ [i]*n for i in ['abc', '123']  ]
[['abc', 'abc', 'abc'], ['123', '123', '123']]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Luis
  • 3,327
  • 6
  • 35
  • 62

2 Answers2

8

Use a nested list comprehension

>>> lst = ['abc', '123']
>>> n = 3
>>> [i for i in lst for j in range(n)]
['abc', 'abc', 'abc', '123', '123', '123']

The idea behind this is, you loop through the list twice and you print each of the element thrice.

See What does "list comprehension" mean? How does it work and how can I use it?

Graham
  • 7,431
  • 18
  • 59
  • 84
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • Side comment: I understand that wouldn't be a nested list? e.g. `[[1,2],[3,4]]`... – Luis Jul 23 '16 at 18:30
  • @Luis Yes, To get a nested list you need to add another pair of brackets. Something like this `[[i for j in range(n)] for i in lst]`. Take an hour off and go through those links. They are one of the best docs and will help you understand list-comps better. All the best. – Bhargav Rao Jul 23 '16 at 18:33
1

It can also be done as:

>>> lst = ['abc', '123']
>>> n=3
>>> [j for i in lst for j in (i,)*n]
['abc', 'abc', 'abc', '123', '123', '123']
shiva
  • 2,535
  • 2
  • 18
  • 32