0

After appending the elements from list a into list b, when list a is cleared it automatically clears the elements of list a in list b. I don't understand how the list b[0] is empty. Can you help me with the error in this code.

a = [1, 2, 3]

b = list()

b.append(a)

a.clear()

print(a)

print(b)

Actual output:

[]

[[]]

Expected output:

[]
[[1, 2, 3]]
Danil Perestoronin
  • 1,063
  • 1
  • 7
  • 9
  • Use `b.append(a.copy())` to generate a new object – mozway Jan 15 '22 at 21:03
  • When you append `a` into your list you are essentially adding a reference to that list object. Meaning any changes you make to `a` will be reflected on what you see in `b[0]`. To prevent this you can create a copy of your list and append this instead like @mozway suggested. The copy is a new object which is then independend of `a`. – Mangochutney Jan 15 '22 at 21:07

0 Answers0