2

exactly the same as Reversing a LinkedList in with multiple assignment

but if you try:

pre, node, node.next = node, node.next, pre

it does not work! (getting NoneType has no attribute next)

both:

pre, node.next, node = node, pre, node.next

and

node.next, pre, node = pre, node, node.next

work. why is the top one wrong? I thought that multiple assignment relieves me from the need to think about the proper order (or to think at all :)


EDIT:

I'll narrow it down:

if node:
   node.next, node = None, node.next
   #node, node.next = node.next, None # comment the previous line and uncomment this - boom!

I always thought that these lines are equivalent...

ihadanny
  • 4,377
  • 7
  • 45
  • 76

1 Answers1

3

The issue is that one of your receiving variables performs an indirection that is based on a value being assigned. The multi-assignment logic saves you from thinking about the right side because it automatically creates temporary storage for the source values. This does not apply to the left side of the assignment however.

So, the order in which node is being assigned matters because of the assignment to node.next.

Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • so it saves me from thinking with my right brain but not from thinking with my left brain? :) – ihadanny Mar 31 '20 at 15:10
  • What’s interesting is that this *could* be made to work, even though the language doesn’t have pointers to *variables* like in C. Each assignment could be preevaluated to one of the canonical forms `x`, `x.a`, or `x[k]` with `x` and (as appropriate) `a` or `k` saved just like the values on the right-hand side. That might, though, be even more surprising in the cases where it matters… – Davis Herring Apr 03 '20 at 02:33
  • I guess it's a design decision. There are use cases where not pre-determining the target recipients may be what's expected/required. In any case knowing how it behaves is the key to obtaining the desired results (e.g. assignments to a property with a setter). – Alain T. Apr 03 '20 at 03:37