| ▲ | PurpleRamen 3 hours ago | |||||||
> I challenge anyone to work out what this code does It's unusual, but pretty obvious. In single steps it's basically this:
which would be b[1]=b because a==1. So this creates a self referencing list. The deeper reason here is, everything is a pointer to data in memory, even if in source code we see the actual data. That's why b[1] is storing the pointer to the list, not the data of the list.If someone is doing BS like this, they deserve spanking. But banning the whole concept because people are unaware or how something is to be used properly is strange. But then again, it seems people have a bit of a problem how python really works and how it's different from other languages. | ||||||||
| ▲ | js2 an hour ago | parent | next [-] | |||||||
Basically, but not quite. :-) The original result for b is:
vs your version:
The equivalent statements to the original chained assignment are:
¹: Using 1 works because the integers -5 thru 256 are interned in cpython. Otherwise, or if you don't want to rely on an implementation detail, to be truly equivalent (i.e. `id(b[1][0]) == id(a)`), it's this: | ||||||||
| ▲ | kccqzy 3 hours ago | parent | prev [-] | |||||||
An adjacent thread has some confusion about whether chained assignments happen left to right or right to left. Honestly that’s a factoid I don’t expect most Python programmers to know. It’s usually a bad idea to rely on people knowing arcade details of a language, especially a language like Python that has attracted many non-programmers like data scientists. (I have nothing against data scientists but their brainpower shouldn’t be wasted on remembering these kind of details.) | ||||||||
| ||||||||