0

I've just started learning python a few weeks back, one of the first things that was taught was how to manipulate lists. Normally if I have a list and want to append a new element it would look something like this.

test_list=[1,2,3]
test_list.append(4)

I just wanted to know why we don't instead say

test_list=test_list.append(4)

This thought came to me because normally for a variable 'x' if we want to update its value, we do the following:

x=initial_value
x=new_value

In the same way for the list case, doesnt test_list.apppend(4) represent a list with the same elements of test_list and contain an extra element 4? In which case why is it that we cant use the same syntax in both cases to update the variable storing the information? In the list case, if I try and print the list I get None and in the x case, if I print x i get new_value?

Vishal Jain
  • 443
  • 4
  • 17
  • 1
    `append` does not return a new list. All it does is modifying the existing list in place. The return type will be `None`. If you want to use an assignment operator, then you'll have to go with `test_list += [4]`. – Vasilis G. Jun 29 '19 at 10:55

2 Answers2

0

A list in Python is more of a class than a type. The function adds an element to the list but does not return anything.

NotNik.
  • 422
  • 3
  • 14
0

This is all about object-oriented programming. If you are no familiar with it, read about it. In short, append is the method of the object which belongs to list class. Basically, this method could behave in 2 ways:

1) like it does, mutating self object

and

2) how you described, generating new object (btw, this is the behaviour of similar Array.concat method in JavaScript)

So, this implementation is just part of language design, the decision made by language creators, and we just have to admit and use it this way :)

oxfn
  • 6,590
  • 2
  • 26
  • 34