+ 5

Why can’t you directly use the insert method on a list? (see description)

words = ["Python", "fun"] words.insert(1, 15) print(words) print(["Python","fun"].insert(1,15)) Output: ['Python', 15, 'fun'] None

23rd Aug 2018, 6:42 PM
Roger Wang
Roger Wang - avatar
7 odpowiedzi
+ 11
In addition to what Eduardo Petry said, python adds an implicit "return None" to every function that doesn't have an explicit return statement. So technically every function that doesn't return anything will return None, even print(): print(print('hi')) Output: > hi > None
23rd Aug 2018, 7:57 PM
Anna
Anna - avatar
+ 12
The `insert` function is a procedure you do onto an already existing list and it returns None (does not return the modified list).
23rd Aug 2018, 6:44 PM
Eduardo Petry
Eduardo Petry - avatar
+ 7
Imagine a function add(a, b) that adds two numbers and returns the sum. If you use print(add(5,3)), the return value 8 is printed. Now imagine another function that does something (like insert something into a list), but doesn't return anything. If you print the function call like this: print(list. insert(position, item)), it will print None because the insert function isn't meant to return anything.
23rd Aug 2018, 8:57 PM
Anna
Anna - avatar
+ 6
Ohhh I get it now, thanks Anna! 😁
23rd Aug 2018, 9:03 PM
Roger Wang
Roger Wang - avatar
+ 5
Anna I think I get your example, but how exactly does my last line of code not have a return statement?
23rd Aug 2018, 8:45 PM
Roger Wang
Roger Wang - avatar
4th Sep 2018, 9:26 PM
Mohamed abd elsadk
Mohamed abd elsadk  - avatar
0
Roger Wang it's not the last line of your code, it's the last line of the builtin list.insert() function
9th Apr 2019, 12:29 AM
FranchuFranchu
FranchuFranchu - avatar