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)
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)
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
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)
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']