Mark Engelberg wrote:
That reminds me of a similar gotcha I've unfortunately run into on
more than one occasion.

# intialize a to be a list of 5 empty lists
a = 5*[[]]
# push a value onto the first list.
a[0].append(1)

What's a?

The result actually makes sense, although I did guess it wrong. :>(

>>> a = b = [1,2,3]
>>> c = [a,b]  # a list with two references to the same object

>>> id(c[0])
3626848
>>> id(c[1])
3626848

>>> c[0][0] = 5
>>> a
[5, 2, 3]

What is b?

Would you rather have Python do something different?


When taking shortcuts like a = 5*[[]], never trust, always verify.

-- Dave

_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to