+ 4
[Solved] effect of .append() method on a list in a for loop.
Hello dear friends, can you please explain the output of "b" in this code? I thought "b" and "c" should look like the same but they're not! This is the code: a = list() b = dict() c = dict() for n in range(3): a.append(n) b[n] = a c[n] = list(a) print(b) # {0 : [0,1,2], 1 : [0,1,2], 2 : [0,1,2]} print(c) # {0 : [0], 1 : [0,1], 2 : [0,1,2]} Thank you for your time guys. 🙏
1 Resposta
+ 4
list(a) creates a new object. So in your loop you add the same object (which itself gets modified in each iteration) three times to b, but three different objects to c.