4

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)
yatu
  • 86,083
  • 12
  • 84
  • 139
barciewicz
  • 3,511
  • 6
  • 32
  • 72
  • 2
    Refer [this](https://stackoverflow.com/questions/1682567/why-does-list-append-evaluate-to-false-in-a-boolean-context) for why it is bad idea to append and assign it in same line. – Sociopath Jan 03 '19 at 09:42
  • 5
    if you know beforehand that `'dan'` will be added to the list, why not initialize it with `'dan'` already in it? I fail to think of a real-life practical scenario for your question.. – Ma0 Jan 03 '19 at 09:43

3 Answers3

5

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

yatu
  • 86,083
  • 12
  • 84
  • 139
0

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)
finefoot
  • 9,914
  • 7
  • 59
  • 102
0
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']
ycx
  • 3,155
  • 3
  • 14
  • 26