0

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

Manuel Montoya
  • 1,206
  • 13
  • 25

1 Answers1

1

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).

Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31