+ 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?
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)
+ 3
the add1 function doesn't return a value, so it returns none by default:
def add1(arg):
return arg+1
+ 3
Thanks everyone
+ 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
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)