+ 2

Why the output is None ?

I am not sure why the output is none here ? lst=[].append(5) print(lst) I believe it is because of [] but I am not sure how would be the correct output?

19th Nov 2019, 6:22 PM
THEGreatGatsby
THEGreatGatsby - avatar
21 Answers
+ 12
The append method does not return a value at all. The [] object is not assigned to a variable, so its modification is lost forever, because you have no chance to access the object.
19th Nov 2019, 6:31 PM
Michael
Michael - avatar
+ 4
You can try this, it will work: lst = [1] #lst = lst.append(5) # <--- don't use this lst.append(5) print(lst) #output = [1,5]
19th Nov 2019, 6:53 PM
Lothar
Lothar - avatar
+ 4
~ swim ~ I quote the official Python documentation: "The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.” (https://docs.python.org/3/library/stdtypes.html) The Null object “is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name).” (https://docs.python.org/3/library/stdtypes.html#the-null-object)
19th Nov 2019, 7:28 PM
Michael
Michael - avatar
+ 3
MirielleđŸ¶ [Inactive] You are right, but I have never argued that there is a “null” in Python. Nevertheless there is a “Null object” in the meaning of a design pattern, which is an established term. It is also the terminology in the official Python documentation. The Null object in Python is implemented via the class NoneType which has None as its sole instance.
19th Nov 2019, 8:24 PM
Michael
Michael - avatar
+ 2
This method changed the list immediately in place and it returns none, this works with sequences that are not constants. For example, you can take a str and a list, and append and replace methods, the append list method will change the existing list without creating a new one, and the str method will return a new str with the changes
19th Nov 2019, 8:42 PM
Artem
Artem - avatar
+ 1
but in our case we are appening value 5 ? so why not 5 for answe?
19th Nov 2019, 6:28 PM
THEGreatGatsby
THEGreatGatsby - avatar
+ 1
do you mean that if append with value would return value in case lst[1]?
19th Nov 2019, 6:29 PM
THEGreatGatsby
THEGreatGatsby - avatar
+ 1
Also try to avoid typing little L because you can easily confuse it with a big i. I <—> l (One can read your code as 1st or as the short form of List)
20th Nov 2019, 11:05 PM
Max_Mnemo
Max_Mnemo - avatar
+ 1
Oh am sorry. i raised my query in higher window.will surely delete it.pls ignore.by the way thanks for the reply.i got my answer in your reply.
27th Nov 2019, 5:54 PM
Vision
Vision - avatar
0
so if we replace append with sort(),add() the result would be the same ? Is that correct?
19th Nov 2019, 6:37 PM
THEGreatGatsby
THEGreatGatsby - avatar
0
what method is returning explicit value in python?
19th Nov 2019, 6:40 PM
THEGreatGatsby
THEGreatGatsby - avatar