Cam
Cam

Reputation: 51

Cannot append to my list without getting a nonetype object error

str1 = []
x = sentence.lower()
x = x.strip('.')
x = x.strip('!')
lsent = x.split()
for e in lsent:
    if e != 'the' and e != 'is' and e != 'if' and e != 'it':
        str1 = str1.append(e)
str1 = " ".join(str1)
print(str1)

Heres my code. When I try to append an item to the end of the list it tells me str1 is a nonetype object even though I made it a list in the first row.

Any help is appreciated I'm thoroughly confused.

Upvotes: 0

Views: 50

Answers (2)

Javier
Javier

Reputation: 1087

The append method to a List modifies it in place and returns a None. Change it for

str1.append(e)

And just to be fair with other users, this was answered at least a couple of times. ;-) For instance, https://stackoverflow.com/a/16641831/2705572

P.S.: In any case, it is always good to answer :-) Welcome to our Community!

Upvotes: 1

jarthur
jarthur

Reputation: 422

Python List.append() method returns the value of None. What you are trying to do, can be done simply by changing

str1 = str1.append(e)

to

str1.append(e)

Upvotes: 3

Related Questions