Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Behavior of Extend with a list in Python [duplicate]

I am trying to understand how extend works in Python and it is not quite doing what I would expect. For instance:

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

But I would have expected:

[4, 5, 6, 1, 2, 3]

Why is that returning a None instead of extending the list?

like image 535
TimothyAWiseman Avatar asked Sep 21 '11 22:09

TimothyAWiseman


3 Answers

The extend() method appends to the existing array and returns None. In your case, you are creating an array — [4, 5, 6] — on the fly, extending it and then discarding it. The variable b ends up with the return value of None.

like image 79
Marcelo Cantos Avatar answered Nov 18 '22 11:11

Marcelo Cantos


list methods operate in-place for the most part, and return None.

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> b.extend(a)
>>> b
[4, 5, 6, 1, 2, 3]
like image 33
Ignacio Vazquez-Abrams Avatar answered Nov 18 '22 09:11

Ignacio Vazquez-Abrams


Others have pointed out many list methods, particularly those that mutate the list, return None rather than a reference to the list. The reason they do this is so that you don't get confused about whether a copy of the list is made. If you could write a = b.extend([4, 5, 6]) then is a a reference to the same list as b? Was b modified by the statement? By returning None instead of the mutated list, such a statement is made useless, you figure out quickly that a doesn't have in it what you thought it did, and you learn to just write b.extend(...) instead. Thus the lack of clarity is removed.

like image 6
kindall Avatar answered Nov 18 '22 11:11

kindall