In Python, I cannot create a list in which every item is a different list. This is an example:
a = [1,2,3,4,5,6,7,8,9]
b = []
c = []
for i in a:
b.append(i)
c.append(b)
c
the result is:
[[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9]]
instead, what I would reach is:
[[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7, 8],
[1, 2, 3, 4, 5, 6, 7, 8, 9]]
May you please help me?
2 Answers 2
By doing c.append(b) you're putting the b instance, so b is everywhere in c, and as you fill b you see it in all boxes of c, you need to make a copy with on these ways
c.append(list(b))
c.append(b[:])
Regarding the task itself, I'd propose another way to do it:
for end in a:
c.append(list(range(1, end + 1)))
Which corresponds to c = [list(range(1, end + 1)) for end in a] in list comprehension
Comments
In Python, variables holds references to the Objects. When you append your list b to another list c, you basically copy the reference of b to your list c (NOT THE OBJECT'S CONTENT). Since, list are mutuable, when you modify your list b (after appending it to list c), it's updated value will also be reflected in c.
Try this code to learn more:
a = [10]
c = a
a.append(100)
print(c)
Outputs:
[10, 100]
You can either do:
c.append(b[:])
OR
c.append(list(b))
OR
You can also use deepcopy in Python.
import copy
a = [1,2,3,4,5,6,7,8,9]
b = []
c = []
for i in a:
b.append(i)
c.append(copy.deepcopy(b))
print(c)
c.append(b[:])?bbefore or after you modify it, and append the copy. Otherwise all elements are references to the same list, which you keep updating.res = [[i for i in range(1,j+1)] for j in i]