-1

Use case:
I want to append a new item along with all the existing items in a list to the same list.
Ex:

list = [ 'a', 'b', 'c']

Appending 'd', expecting the output as: ['a', 'b', 'c', 'a', 'b', 'c', 'd']

My code:

list.append(list.append('d'))

Current output:

['a', 'b', 'c', 'd', None]

Why am I getting a None item here and how can I print the list as expected?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 4
    Note: One should avoid shadowing built-in names like `list`. I would recommend using a different variable name. – MSeifert Dec 03 '18 at 12:06

2 Answers2

2

Use list.append('d') instead.

append function in list return nothing and so list.append(list.append('d')) will be added None.

To print the expected list (let the list be 'l'):

list_old = list(l)
l += l # ['a', 'b', 'c'] -> ['a', 'b', 'c', 'a', 'b', 'c']
l.append('d')
list_old.extend(l)
1

list.append returns None. This is because list.append is an in-place operation. In addition, you are shadowing a built-in, which is not recommended.

You can append to a copy, then extend your original list:

L = ['a', 'b', 'c']
L_to_append = L.copy()
L_to_append.append('d')
L.extend(L_to_append)

But this is verbose. You can just use the += operator:

L = ['a', 'b', 'c']
L += L + ['d']

print(L)

['a', 'b', 'c', 'a', 'b', 'c', 'd']
jpp
  • 159,742
  • 34
  • 281
  • 339