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))
Asked By: Manish Giri

||

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.

Answered By: ojii
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.