Hello world!
First, a super brief introduction: my name is Ry, and I’m midway through a web development bootcamp in Chicago. I was a consultant fo...
For further actions, you may consider blocking this person and/or reporting abuse
Hi Ry! I laughed reading this so it's a good start :-)
What you're experiencing is a combination of how Python syntax works and the fact that lists are mutable objects.
In the first example:
you're telling Python: "make sleeve a list of five numbers and then make shirt a list of five sleeves". So Python is going to copy the object pointed by the variable
sleeve
inside shirt five time, but it's the same object. You can easily see it like this:id()
is a function that returns the memory identity (address) of the object. As you can see, it's all the same objectThe second example is basically the same, you're telling Python to multiply by five times the same list:
In the third example you're actually building a new list for each iteration in the list comprehension, so it works:
:-)
! 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?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:
they all are the same object in memory but since you can't change it, it's fine.
Ooooohh, that makes sense -- thank you!!
The answer is really simple: how many lists do you make? If you really want a 5x5 zero matrix, it's quite obvious you need 6 lists. If you make only 2 of them, some (many) of them are going to be the same.