0

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 ?

3 Answers 3

3

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)]
Sign up to request clarification or add additional context in comments.

2 Comments

OMG, whyever didn't I think of THAT ? Thanks too ! (I'll have a hard time choosing one to accept …)
While the accepted answer by @duckboycool is perfectly good and works, I find this answer more intuitive.
1

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

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

1 Comment

Wow, cool, I would never have thought of this ! Thanks a lot !
1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.