reverse a linked list with multiple assignment - not all assignment orders work?

ihadanny :

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...

Alain T. :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379751&siteId=1