1

I have a list which I appended a value and then use the new list to call a function, I would like to do that in one line but is not working...

list = ['a', 'b']
my_funtion(list.append('c'))

my_function received a None instead the list with the three letters which is correct because from doc:

def append(self, p_object):
    """ L.append(object) -> None -- append object to end """
    pass

it works if I do:

list = ['a', 'b']
list.append('c')
my_funtion(list)

I would like to know if there is way to simplify the code with my original sample.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Tincho
  • 21
  • 3
  • Don't use `list` as a variable name as it will stomp on the builtin type. `list.append()` modifies the object in place and returns `None`. – pault Aug 22 '18 at 20:50
  • 2
    Possible duplicate of [Why does append return none in this code?](https://stackoverflow.com/questions/16641119/why-does-append-return-none-in-this-code) – pault Aug 22 '18 at 20:51
  • Incidentally, this wouldn't have worked even in Java. In Java, `List.add` returns `true`. – user2357112 Aug 22 '18 at 20:53

2 Answers2

4

You can use:

L = ['a', 'b']
my_funtion(L + ['c'])

which concatenates the single-item list ['c'] with the L list to create a new list ['a', 'b', 'c'] as the parameter to my_function.

Since this creates a new list, the original list L in the caller won't be affected by either the concatenation or by mutations performed on it within the function. If you want to permanently mutate your original list with the added element and pass it by reference to your function, stick to your original approach with append before making the function call.

Note that in your original example, when you call a variable list, you've redefined the builtin function list(), which converts an iterable to a list, so please use caution in choosing your variable names.

See also Why does append() always return None in Python?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
1

In python, an argument is defined as A value provided to a function when the function is called. type(list.append()) returns a Nonetype. This is explained in this thread What is a 'NoneType' object?. As far as I know, there is no built-in list method in python returns the modified list.In short answer from @ggorlen is probably the best, because l + ['c'] returns a list. or you can write your own append function

Ruiyang Li
  • 94
  • 1
  • 8