0

I am new to python programming why this assignment value to k is giving 'None' value

> >>> l=[2,3,4]
> >>> k=l.append(14)
> >>> print k
None
> >>> print l
[2, 3, 4, 14]

in above example List,I append the 14 value to list and then assigned to k but k is printing None please tell me the reason why its printing None instead of appended list?

Thanks mukthyar

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
Rubia
  • 445
  • 2
  • 6
  • 17

5 Answers5

7

append changes the current list and doesn't return anything. Use:

k = l + [14]

or

k = l[:]       # Copy list
k.append(14)
citxx
  • 2,525
  • 17
  • 40
4

Most methods in Python which mutate their instance (.append(), .sort(), et al.) do not return a copy of the object. Thus l.append(X) does actually return "None" just as l.sort() would.

You'd probably want to use something more like:

l.append(14)
k = l[-1]
Jim Dennis
  • 17,054
  • 13
  • 68
  • 116
1

What you are seeing is expected - the list.append method does not return the modified list. If you take a look at the relevant section of the Python tutorial, you'll notice that methods which return useful values are documented as such.

Working in the interactive interpreter, you can tell that the expression yields None by the lack of output:

>>> l = [1, 2, 3]
>>> l.append(14)
>>>

If (theoretically) list.append returned the list, you would see the following instead:

>>> l = [1, 2, 3]
>>> l.append(14)
[1, 2, 3, 14]
>>>

Using the interactive interpreter this way can save you from printing every value.

AerandiR
  • 5,260
  • 2
  • 20
  • 22
1

In python default return type is None so if your function is not return any value then you will get the None from that function. There are different functions for the object. Some functions are perform on same object and others are return the modified copy. For example list.sort will change the original list while sorted will return the new sorted list without changing the original one. So append is working on object so it will change the object value instead of returning new modified copy.

Hope this will make your view clear about append method.

Nilesh
  • 20,521
  • 16
  • 92
  • 148
1

from python document

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

in simple word append function returns nothing but None

suggested reading

akhter wahab
  • 4,045
  • 1
  • 25
  • 47