What's the difference in the extend and append methods when applying them while creating a list and after having created the list

Question:

I’d like to know why when using the methods of append and extend while creating a list, the code returns none, but when they are applied after creating the list, the result is as expected.

Here is the code:

mylist = list(range(1,10))
mylist.extend(list(range(20,30)))
print(mylist)

mylist = list(range(1,10))
mylist.append(list(range(20,30)))
print(mylist)

This results in [1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

And [1, 2, 3, 4, 5, 6, 7, 8, 9, [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]

But when using

mylist = list(range(1,10)).extend(list(range(20,30)))
print(mylist)

mylist = list(range(1,10)).extend(list(range(20,30)))
print(mylist)

They both result in None

I am using python 3.7.0

Asked By: Manuel Montoya

||

Answers:

Neither list.extend nor list.append return values; they only modify their object.

If you want to create a new list and assign it to a different variable, you should use the + operator.

(But note that in your example code you’re using .extend twice, rather than .append).

Answered By: Christoph Burschka
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.