Home > Net >  Is there a way to add an amount of lists, and append that to a list?
Is there a way to add an amount of lists, and append that to a list?

Time:09-24

Basically, i want a list, which contains an increasing number of lists, (which I've now getten the answer to):

l = []
for i in range(3):
    l.extend([[i] for _ in range(i 1)])
print(l)

output: [[0], [1], [1], [2], [2], [2]]

But i want to 'group' the numbers together, so the output is: [[[0]], [[1], [1]], [[2], [2], [2]]]

CodePudding user response:

You can use extend to add multiple items to the end of a list.

li = []
for i in range(3):
    li.extend([[] for _ in range(i)])

CodePudding user response:

New answer

Now that you've provided a clear example of your desired output,

In [9]: top = 1  # starting number

In [10]: num_rows = 4

In [11]: [[[top   i] for _ in range(i   1)] for i in range(num_rows)]
Out[11]: [[[1]], [[2], [2]], [[3], [3], [3]], [[4], [4], [4], [4]]]

Old answer

Your three different example outputs all seem to contradict each other in various ways, and as such your question is very confusing, hence the vastly different results produced by the current answers.

In [1]: top = 4  # starting number, at the top of the pyramid

In [2]: num_rows = 5

In [3]: pyramid = [[(top   i) for _ in range(i   1)] for i in range(num_rows)]

In [4]: pyramid
Out[4]:
[[4], [5, 5], [6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8, 8]]

In [5]: for row in pyramid:
    ...:     print(*row)
    ...:
4
5 5
6 6 6
7 7 7 7
8 8 8 8 8

If also want to print them centered:

In [7]: width = 2 * num_rows - 1

In [8]: print("\n".join(" ".join(map(str, row)).center(width) for row in pyramid))
    4
   5 5
  6 6 6
 7 7 7 7
8 8 8 8 8

CodePudding user response:

Use a list comprehension inside the for loop to create i 1 lists. Use extend() to add all these to the main list.

ls = []
for i in range(3):
    ls.extend([[i] for _ in range(i 1)])
print(ls)
# [[0], [1], [1], [2], [2], [2]]
  • Related