TheEagle
TheEagle

Reputation: 5992

How to generate list with repeating items?

Suppose I want to create a list like the following with a list comprehension:

["2", "2", "2", "3", "3", "3", "4", "4", "4"]

I have tried:

>>> [*[str(n)] * 3 for n in range(2, 5)]

  File "<stdin>", line 1
SyntaxError: iterable unpacking cannot be used in comprehension

and

>>> [str(n) * 3 for n in range(2, 5)]
['222', '333', '444']

where I got the numbers, but together in one string, and

>>> [[str(n)] * 3 for n in range(2, 5)]
[['2', '2', '2'], ['3', '3', '3'], ['4', '4', '4']]

where I got a nested list, but want a flat one. Can this be done in a simple way, or do I have to take the nested list method and flatten the list ?

Upvotes: 0

Views: 48

Answers (3)

Marios Mitalidis
Marios Mitalidis

Reputation: 118

You can use the function chain function from the itertools library in order to flatten the list.

>>> from itertools import chain
>>> list(chain(*[[str(n)] * 3 for n in range(2, 5)]))
['2', '2', '2', '3', '3', '3', '4', '4', '4']

Upvotes: 1

Kevin Eldurson
Kevin Eldurson

Reputation: 190

A nested for loop is your best bet. I think this is the simplest solution:

[str(n) for n in range(2, 5) for i in range(3)]

Upvotes: 3

duckboycool
duckboycool

Reputation: 2455

A simple way you could do this with list comprehension is by using integer division.

[str(n // 3) for n in range(6, 15)]

Upvotes: 1

Related Questions