3

I just started out learning python and am playing around with list methods. I bumped into this problem; assigning list.extend to a variable doesn't work the way I thought it would and I'm not sure why.

alph = ["a", "b", "c"]
num = [0, 1, 2,]

num_alph = alph.extend(num)
print num_alph

Printing num_alph results in none but I was expecting it print this; ["a", "b", "c", 0, 1, 2]

Rewriting the code to this gets me the expected result:

alph = ["a", "b", "c"]
num = [0, 1, 2,]

alph.extend(num)
num_alph = alph
print num_alph

Why does my former code print none instead of the extended list?

2
  • Because list.extend() returns None; all methods that alter the object in-place do so.
    – Martijn Pieters
    Dec 20, 2015 at 23:23
  • Got it. Thanks a lot!!
    – wcj
    Dec 22, 2015 at 22:57

1 Answer 1

2

.extend() alters the content of the list in-place. It doesn't create a new one with the appended elements to it so doesn't make sense returning the same list. If you want alph to remain unchanged after extend, you should create a new list:

>>> num_alph = alph + num
>>> print num_alph
['a', 'b', 'c', 0, 1, 2]

--

>>> alph.extend(num)
>>> print alph
['a', 'b', 'c', 0, 1, 2]
1
  • 1
    It is like .sort().
    – cwahls
    Dec 20, 2015 at 23:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.