Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list extension and variable assignment [duplicate]

I tried to extend a list and was puzzled by having the result return with the value None. What I tried was this:

>>> a = [1,2]  
>>> b = [3,4]  
>>> a = a.extend(b)  
>>> print a  

None

I finally realized that the problem was the redundant assignment to 'a' at the end. So this works:

>>> a = [1,2]  
>>> b = [3,4]  
>>> a.extend(b)  
>>> print a  

[1,2,3,4]

What I don't understand is why the first version didn't work. The assignment to 'a' was redundant, but why did it break the operation?

like image 939
monotasker Avatar asked Dec 12 '25 01:12

monotasker


1 Answers

Because, as you noticed, the return value of extend is None. This is common in the Python standard library; destructive operations return None, i.e. no value, so you won't be tempted to use them as if they were pure functions. Read Guido's explanation of this design choice.

E.g., the sort method on lists returns None as well, while the non-destructive sorted function returns a value.

like image 122
Fred Foo Avatar answered Dec 14 '25 20:12

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!