1

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.

ferdy
  • 6,870
  • 3
  • 34
  • 45
  • 2
    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`. – Martijn Pieters Jun 06 '15 at 08:48
  • 1
    What you're trying to print is `[].append(2)` and not `foo` itself. `foo = [2]` or `foo = []; foo.append(2)` will do. – raymelfrancisco Jun 06 '15 at 08:50
  • @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. – ferdy Jun 06 '15 at 09:00
  • 2
    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. – Alexander McFarlane Jun 06 '15 at 09:23

1 Answers1

7

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.

Alexander McFarlane
  • 9,832
  • 8
  • 52
  • 96
  • Thanks for answering. I already knew how to do it, but I was asking myself why the first syntax wouldn't work. – ferdy Jun 06 '15 at 09:02
  • 1
    @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. – Alexander McFarlane Jun 06 '15 at 09:25