-2

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))
Manish Giri
  • 3,284
  • 7
  • 42
  • 76
  • Python's way of doing things with mutable objects are different The built in .extend() method and other built in methods such as .append(), returns none because it is understood in python that the object itself will actually change..these built in methods **makes** the changes but does not print the **changes** because of the mutabile nature of list objects. To see your new list you will need to print the old list that has the appended data – repzero Oct 19 '15 at 04:05

1 Answers1

0

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.

ojii
  • 4,604
  • 1
  • 23
  • 32