Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning to list.extend to variable in python 2.7 [duplicate]

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?

like image 931
wcj Avatar asked Dec 07 '25 05:12

wcj


1 Answers

.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]
like image 167
Ozgur Vatansever Avatar answered Dec 08 '25 19:12

Ozgur Vatansever



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!