Best practice to append value to an empty list
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.
Comments
-
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 about 9 yearsSo why not just use
foo = [2]
? There is no need to callappend
at all when you can just specify the initial values directly.list.append()
alters the list in-place so always returnsNone
. -
raymelfrancisco about 9 yearsWhat you're trying to print is
[].append(2)
and notfoo
itself.foo = [2]
orfoo = []; foo.append(2)
will do. -
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 about 9 yearsI 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 about 9 yearsThanks for answering. I already knew how to do it, but I was asking myself why the first syntax wouldn't work.
-
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.