Python: how to append to a list in the same line the list is declared?

Question:

Is there any way to replace the following:

names = ['john', 'mike', 'james']
names.append('dan')
print(names)

with a one-liner similiar to this one (which will print None)?:

names = ['john', 'mike', 'james'].append('dan')
print(names)
Asked By: barciewicz

||

Answers:

How about a adding them?

print(['john', 'mike', 'james'] + ['Dan'])
['john', 'mike', 'james', 'Dan']

Note that you have to add the second element as a list as you can only add elements of the same type, as it occurs with strings

Answered By: yatu

list.append is an in-place method, so it changes the list in-place and always returns None.

I don’t think you can append elements while declaring the list. You can however, extend the new list by adding another list to the new list:

names = ['john', 'mike', 'james'] + ['dan']
print(names)
Answered By: finefoot
names = ['john', 'mike', 'james']; names.append('dan')
#This is 1 line, note the semi-colon

This is slightly cheating, but then again, I fail to see the purpose of putting it on 1 line. Otherwise, just do as what the others have suggested:

names = ['john', 'mike', 'james'] + ['dan']
Answered By: ycx
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.