updating python list on recurison call returns None
Question:
def get_name():
import random
lst = ["aa", "bbb", "ccc", "dddd", "eee", "stop"]
return random.choice(lst)
def poi(name, lst):
res = get_name()
lst.append(res)
if res !="stop":
poi(name, lst)
else:
print lst
return lst
if __name__ == '__main__':
print poi("xx", [])
poi()
method add items in a passed list and should return list until “stop” is in the list. If “stop” is in the list then returns the list
print lst
prints ['bbb', 'dddd', 'bbb', 'stop']
#1
But
`print poi("xx", [])` prints `None` #2
Why #2
is printing None
instead of updated list ?
Answers:
The
poi(name, lst)
should be
return poi(name, lst)
Without the return
statement, the function is implicitly returning None
.
def get_name():
import random
lst = ["aa", "bbb", "ccc", "dddd", "eee", "stop"]
return random.choice(lst)
def poi(name, lst):
res = get_name()
lst.append(res)
if res !="stop":
poi(name, lst)
else:
print lst
return lst
if __name__ == '__main__':
print poi("xx", [])
poi()
method add items in a passed list and should return list until “stop” is in the list. If “stop” is in the list then returns the list
print lst
prints ['bbb', 'dddd', 'bbb', 'stop']
#1
But
`print poi("xx", [])` prints `None` #2
Why #2
is printing None
instead of updated list ?
The
poi(name, lst)
should be
return poi(name, lst)
Without the return
statement, the function is implicitly returning None
.