DEV Community

Discussion on: TIL: Python Comprehensions Make Matrices Work

Collapse
 
rsdesoto profile image
Ry

! This makes significantly more sense -- thank you!

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

Collapse
 
rhymes profile image
rhymes

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.

Thread Thread
 
rsdesoto profile image
Ry

Ooooohh, that makes sense -- thank you!!