0

I'm doing an exercise that asks to move all the zeroes to the end of a list, tried several solutions for practice, all worked, but the one I thought was the most pythonic one using .extend() doesn't work and returns None.

This works:

my_list = [0, 0, 1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 0]

def move_zeros(my_list):
    l = [x for x in my_list if x != 0]
    z = [y for y in my_list if y == 0]
    l.extend(z)
    return l

print(move_zeros(my_list))

This also works:

def move_zeros(my_list):
    l = [x for x in my_list if x != 0]
    l.extend([y for y in my_list if y == 0])
    return l

print(move_zeros(my_list))

But this doesn't work, returns None:

def move_zeros(my_list):
    l = [x for x in my_list if x != 0].extend([y for y in my_list if y == 0])
    return l

print(move_zeros(my_list))
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Diego C.
  • 11
  • 2

1 Answers1

1

The assignment causes it to return None. The return value of extend() is None, so l = None when l = any_list.extend(any_other_list).

The documentation makes this clear:

help(list.extend())


Help on method_descriptor:

extend(...)
    L.extend(iterable) -> None -- extend list by appending elements from the iterable
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Michael Ruth
  • 2,938
  • 1
  • 20
  • 27