0

I wanted to add a word to my list so the following code works.

text = 'A quick brown fox jumps over the lazy dog'
x = text.split()
print(x)

x.append('cat')
print(x)

But when I assign >> x.append('cat') << to another variable y, my code is evaluated to None. Why is that so? Shouldn't they both give me the same output? Code is as follows...

 text = 'A quick brown fox jumps over the lazy dog'

 x = text.split()
 print(x)

 y = x.append('cat')
 print(y)
  • What did you think think `x.append` would return? – chepner Dec 30 '20 at 21:11
  • `x.append('cat')` is a function, which adds new element to `x`, doesn't return new `x`, but `None` instead – Grzegorz Skibinski Dec 30 '20 at 21:11
  • tl;dr `append` modifies the list in place so it doesn't feel the need to return a value. If you want to add a value onto the end of the list and obtain a new list use `y = x + ['cat']`, or if you're fine with `x` and `y` both being modified (and pointing to the same part of memory) then just do `x.append('cat')` followed by `y = x`. – Aplet123 Dec 30 '20 at 21:11

2 Answers2

0

because list.append() does not return anything. Its an inplace operation, it just modifies the list, does not create another a copy of modified list.

pratham
  • 47
  • 4
0

The reason is that x.append does not return a value, it only mutates the original array with the new value added.

use y = x + ['cat'] to assign it to a new variable or

x.append('cat')
y = x

to also modify the original.

Raspberry1111
  • 78
  • 3
  • 4