John Smith
John Smith

Reputation: 151

Variables becoming Type:None in Python

I have two sets of code for taking the list A=[1,2,3] and changing A into [1,2,3,4].

Here is the first code, followed by what it prints.

A=[1,2,3]
A.append(4)
print(type(A))
print(A)

<class 'list'>
[1, 2, 3, 4]

This first code works.

Here is the second code, followed by what it prints.

A=[1,2,3]
A=A.append(4)
print(type(A))
print(A)

<class 'NoneType'>
None

This second code returns None.

For example, suppose I want to turn 'no no no' into 'yeah yeah yeah':

text='no no no'
text=text.replace('no','yeah')
text

'yeah yeah yeah'

text='no no no'

text.replace('no','yeah')

text

'no no no'

So now the situation is reversed. So you just have to learn which one is correct for each method?

Upvotes: 0

Views: 1350

Answers (1)

lambdawaff
lambdawaff

Reputation: 141

When you put A=A.append(4), you are assigning to the variable A the return value of A.append(4), which is None.

The append() function is an in-place function, meaning that it modifies your original list when you call it - it does not return the modified list.

To be more exact, when you execute the line A=A.append(4),

  1. The append(4) function is called, and the value of A is [1, 2, 3, 4]
  2. ...and then the value returned by append(4) - which is none - is immediately assigned to A.

Whatever append() does to your list is discarded, since the line ultimately evaluates to A=None because of this.

This is different than replace(), which does return the new, modified value of the string. To answer your question, yes, you would just have to check the documentation on an individual basis to know the correct usage for each function.

Upvotes: 2

Related Questions