-1

Easy question here.

In Python 3 -why is this meaningful?:

  x=[1,2,3]
  y=[4,5,6]
  tst=x.append(y)

But this gives you nothing - even though it is the same thing

tst=[1,2,3].append([4,5,6])
Dano13
  • 149
  • 9
  • 2
    Does this answer your question? [Assign value of a list into another list while using append or insert method returning None as output](https://stackoverflow.com/questions/48175707/assign-value-of-a-list-into-another-list-while-using-append-or-insert-method-ret) – kaya3 Apr 07 '20 at 14:47
  • 1
    In both cases `tst` will have `None`. The difference is that in the first one you actually append to another object while in the second you append to a list literal which doesn't affect anything... – Tomerikoo Apr 07 '20 at 14:54

2 Answers2

1

Return value of x.append(...) is None so it's waste of time to save it in tst variable ! To add all of y items to the end of x you can do something as below :

tst = x + y 
AmirHmZ
  • 516
  • 3
  • 22
1

tst points to the result of the append method on the object [1, 2, 3] which is None since append returns nothing, it just mutates the object.

>>> type(tst)
<class 'NoneType'>

If you, however, create a variable that points to the mutable object [1, 2, 3]:

tst = [1,2,3]
tst.append([4,5,6])

You get the desired result:

>>> tst
[1, 2, 3, [4, 5, 6]]

In other words, append does not return back a list but mutates the object.

Rafael
  • 7,002
  • 5
  • 43
  • 52