Best practice to append value to an empty list

33,976

The actual reason why you can't do either of the following,

l = [].append(2)
l = [2,3,4].append(1)

is because .append() always returns None as a function return value. .append() is meant to be done in place.

See here for docs on data structures. As a summary, if you want to initialise a value in a list do:

l = [2]

If you want to initialise an empty list to use within a function / operation do something like below:

l = []
for x in range(10):
    value = a_function_or_operation()
    l.append(value)

Finally, if you really want to do an evaluation like l = [2,3,4].append(), use the + operator like:

l1 = []+[2]
l2 = [2,3,4] + [2]
print l1, l2
>>> [2] [2, 3, 4, 2]   

This is generally how you initialise lists.

Share:
33,976
ferdy
Author by

ferdy

{writer, photographer, code}

Updated on June 06, 2020

Comments

  • ferdy
    ferdy about 4 years

    I'm just curious about the following code fragment not working, which should initialize an empty list and on-the-fly append an initial value. The second fragment is working. What's wrong with it? Is there a best practice for such initializing?

    >>> foo = [].append(2)
    >>> print foo
    None
    >>> foo = []
    >>> foo.append(2)
    >>> print foo
    [2]
    

    EDIT: Seems I had a misunderstanding in the syntax. As already pointed out below, append always returns None as a result value. What I first thought was that [] would return an empty list object where the append should put a first element in it and in turn assigns the list to foo. That was wrong.

    • Martijn Pieters
      Martijn Pieters about 9 years
      So why not just use foo = [2]? There is no need to call append at all when you can just specify the initial values directly. list.append() alters the list in-place so always returns None.
    • raymelfrancisco
      raymelfrancisco about 9 years
      What you're trying to print is [].append(2) and not foo itself. foo = [2] or foo = []; foo.append(2) will do.
    • ferdy
      ferdy about 9 years
      @raymelfrancisco Thanks for answering my simple question. I can't explain, why this has to be downvoted. Some people may already have sought up knowledge by breast feeding. Thanks.
    • Alexander McFarlane
      Alexander McFarlane about 9 years
      I think his question was really asking the question of why you could not do a theoretical operation like foo =[].append(2) as it would clearly make no sense to do this normally.
  • ferdy
    ferdy about 9 years
    Thanks for answering. I already knew how to do it, but I was asking myself why the first syntax wouldn't work.
  • Alexander McFarlane
    Alexander McFarlane about 9 years
    @ferdy - I've edited my answer to include all the knowledge I have on the topic. Initially my answer was badly worded. Hopefully, my edited version makes more sense.