Lists acting weird , operations+ indexing=None | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Lists acting weird , operations+ indexing=None

here is my code: a=[1,2,3,4,5] print(a) def add1(arg): arg=arg+1 for i in range(len(a)): print(a[i]) k=a[i] a[i]=add1(k) print(a[i]) print(a) this should, theoretically, result in [2,3,4,5,6] (and i dont care about efficiency, i just found this as an example) but instead it is: [None, None, None, None, None] Why? And how do i fix it?

12th Dec 2023, 2:03 PM
5Just
5Just - avatar
5 Antworten
+ 5
5Just , after having implemented the *return* statement in the function add1(), we can additionally simplify the rest of the code, meaning the *for loop*. this would look like: a=[1,2,3,4,5] print(a) def add1(arg): return arg + 1 for i in range(len(a)): a[i] = add1(a[i]) print(a)
12th Dec 2023, 5:07 PM
Lothar
Lothar - avatar
+ 3
the add1 function doesn't return a value, so it returns none by default: def add1(arg): return arg+1
12th Dec 2023, 2:13 PM
Angelo Abi Hanna
Angelo Abi Hanna - avatar
+ 3
Thanks everyone
12th Dec 2023, 2:27 PM
5Just
5Just - avatar
+ 2
It is because the function returns "None". You need to include a return statement at the end of the function to return anything, otherwise it will always return None. Here is the code with explanation. https://sololearn.com/compiler-playground/cVF03G3wAXBt/?ref=app
12th Dec 2023, 2:14 PM
Wong Hei Ming
Wong Hei Ming - avatar
0
x = [1,2,3,4,5] def add1(n): return n+1 for i,v in enumerate(x): x[i] = add1(v) print(x)
12th Dec 2023, 11:08 PM
Bob_Li
Bob_Li - avatar