1

Here is my code:

def list_test(foo):
    bar = foo.append('w')
    return bar

my_input = [7,8,9]

When i run it:

>>>print list_test(my_input)
None

It's printout None. Why? How can I fix that?

Note: Output i need is: 7,8,9,'w'

Thanks.

Michael
  • 14,053
  • 33
  • 90
  • 141

4 Answers4

9

list.append() returns None to underscore the fact that it is a mutating call. Such calls, that modify their argument, generally return None. Calls that create a new list return it.

If it is important that list_test return the modified list, then your code might be better like this:

def list_test(foo):
    foo.append('w')
    return foo

my_input = [7,8,9]

>>> print list_test(my_input)
[7, 8, 9, 'w']
>>> print my_input
[7, 8, 9, 'w']

But, if I were writing this, I would follow the convention that mutating calls return None, and write it this way:

def list_test(foo):
    foo.append('w')

my_input = [7,8,9]

>>> print list_test(my_input)
None
>>> print my_input
[7, 8, 9, 'w']

Finally, if you want list_test to be non-mutating, that is it should return a new list and not modify its input, one of these might work for you:

def list_test(foo):
    new_foo = list(foo)
    new_foo.append('w')
    return new_foo

def list_test(foo):
    return foo + ['w']

my_input = [7,8,9]

>>> print list_test(my_input)
[7, 8, 9, 'w']
>>> print my_input
[7, 8, 9]
Robᵩ
  • 154,489
  • 17
  • 222
  • 296
3

append will not return the list but mutate the original list. So after calling foo.append(), foo’s content changed. As such foo itself is the “new” (and old) list with the new element. So you could just write your function like this:

def list_test(foo):
    foo.append('w')
    return foo

Note that this also means that the original list you passed to the function changed as well:

>>> my_input = [7,8,9]
>>> list_test(my_input)
[7, 8, 9, 'w']
>>> my_input
[7, 8, 9, 'w']
poke
  • 339,995
  • 66
  • 523
  • 574
1

Because append() works in-place, i.e. modifies foo directly instead of creating a new list.

Oberon
  • 3,189
  • 14
  • 28
0

list.append() doen't return anything useful because it only modifies its argument (list). You probably want to return foo instead

RiaD
  • 45,211
  • 10
  • 74
  • 119