This is a question about creating a python list.

Asked 2 years ago, Updated 2 years ago, 13 views

list = [0 for i in range(10)]+[1 for i in range(10)]+ ... +[n for i in range(10)]

I want to make a list using the for statement, but I tried the above code.

Is there an easy way to do it in one sentence because it gets too long when the n gets bigger?

Thank you for your help.

python

2022-09-20 17:38

1 Answers

>>> n = 3
>>> l = [ j for j in range(n) for _ in range(10) ]
>>> l
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
>>> n = 8
>>> l = [ j for j in range(n) for _ in range(10) ]
>>> l
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]


2022-09-20 17:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.