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?
.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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With