1

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?

Ronan Boiteau
10.3k7 gold badges40 silver badges62 bronze badges
asked Mar 23, 2020 at 15:55
3
  • 1
    Perhaps you meant: c.append(b[:])? Commented Mar 23, 2020 at 15:57
  • You need to make a copy of b before or after you modify it, and append the copy. Otherwise all elements are references to the same list, which you keep updating. Commented Mar 23, 2020 at 15:58
  • 1
    res = [[i for i in range(1,j+1)] for j in i] Commented Mar 23, 2020 at 16:00

2 Answers 2

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

answered Mar 23, 2020 at 15:59
Sign up to request clarification or add additional context in comments.

Comments

1

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)
answered Mar 23, 2020 at 16:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.