Different behavior using .extend and concatenation in Python lists
Question:
I read in this tutorial that you could add two lists using either +
or the .extend()
method. Other than performance issues, they produce the same results.
In that case, if I want to return the first and last four items of a list, using slicing, why does the .extend()
return None
while the +
operator returns the correct result for the following code:
# return first and last four items in list
def first_and_last_4(itr):
first_four = itr[:4]
print(first_four)
last_four = itr[-4:]
print(last_four)
# return first_four.extend(last_four)
return first_four + last_four
my_list = list(range(1,50))
print(first_and_last_4(my_list))
Answers:
list.extend
modifies the existing list. It does not return anything. list + list
returns a new list.
In your example, after calling first_four.extend(last_four)
, you should return first_four
.
I read in this tutorial that you could add two lists using either +
or the .extend()
method. Other than performance issues, they produce the same results.
In that case, if I want to return the first and last four items of a list, using slicing, why does the .extend()
return None
while the +
operator returns the correct result for the following code:
# return first and last four items in list
def first_and_last_4(itr):
first_four = itr[:4]
print(first_four)
last_four = itr[-4:]
print(last_four)
# return first_four.extend(last_four)
return first_four + last_four
my_list = list(range(1,50))
print(first_and_last_4(my_list))
list.extend
modifies the existing list. It does not return anything. list + list
returns a new list.
In your example, after calling first_four.extend(last_four)
, you should return first_four
.