News for hackers. Stuff that matters.

So you think you know Python

Quiz: what is the value of foo after this code is run?

foo=[0];bar=[foo];foo[0]=bar

Extra credit:

1) what is bar[0]

2) foo==bar

( 5 comments | 10 points | on HN )
Re:So you think you know Python by jbotz on Friday October 09, 2020 @02:56PM (#24733157)
Well, don't do that.

It's just a circular data structure, many (or even most) languages give you enough rope to hang yourself with one of those. Nothing particularly surprising or Python-specific about it.

Re:So you think you know Python by kazinator on Friday October 09, 2020 @08:00PM (#24735622)
What you have is a circular structure. foo and bar are distinct objects, so foo == bar is false. However, they are similar objects: they have exactly the same structure. If we had a function for structural comparison which handles cycles, that function would have to conclude that foo and bar are structurally equal. This is because of symmetry in the cycle: bar[0] is foo and, symmetrically, foo[0] is bar. Both foo and bar are one-element lists whose elements are, respectively, bar and foo.
Re:So you think you know Python by asicsp on Saturday October 10, 2020 @02:18AM (#24737014)
There's a repo dedicated for such snippets: https://github.com/satwikkansal/wtfpython
Re:So you think you know Python by ddorian43 on Saturday October 10, 2020 @05:40PM (#24742062)
I'm dissappointed.
Re:So you think you know Python by HelloFellowDevs on Friday October 09, 2020 @03:05PM (#24733276)
foo = [bar[foo]]

bar[0] = foo

false

if wrong please correct accordingly.