re: TIL: Python Comprehensions Make Matrices Work VIEW POST


Why does the first [0]*5 not run into the same issues? Is it because this is updating a single list?

That's because Python cheats a little bit. I don't know the exact list of optimizations but you're creating a list of integers so I think it reuses the same object in memory. An integer is an immutable object, it detects you're creating a list of 5 integers, so it just fills up a list of 5 zeroes. You can see what's going on:

>>> s
[0, 0, 0, 0, 0]
>>> [id(x) for x in s]
[4501366592, 4501366592, 4501366592, 4501366592, 4501366592]

they all are the same object in memory but since you can't change it, it's fine.

Ooooohh, that makes sense -- thank you!!

code of conduct - report abuse