27

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?

dreftymac
  • 29,742
  • 25
  • 114
  • 177
TimothyAWiseman
  • 13,397
  • 11
  • 37
  • 47

5 Answers5

41

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.

Marcelo Cantos
  • 174,413
  • 38
  • 319
  • 360
10

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]
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
5

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.

kindall
  • 168,929
  • 32
  • 262
  • 294
4

I had this problem and while the other answers provide correct explanations, the solution/workaround I liked isn't here. Using the addition operator will concatenate lists together and return the result. In my case I was bookkeeping color as a 3-digit list and opacity as a float, but the library needed color as a 4 digit list with opacity as the 4th digit. I didn't want to name a throwaway variable, so this syntax suited my needs:

color = [1, 1, 0]
opacity = 0.75
plot.setColor(color + [opacity])

This creates a new list for opacity on the fly and a new list after the concatenation, but that's fine for my purposes. I just wanted compact syntax for extending a list with a float and returning the resulting list without affecting the original list or float.

flutefreak7
  • 2,121
  • 3
  • 26
  • 35
4

extend extends its operand, but doesn't return a value. If you had done:

b = [4, 5, 6]
b.extend(a)

Then you would get the expected result.

Tom Zych
  • 12,899
  • 9
  • 35
  • 52