Function don't update the list realtime python
Question:
def func(a,b):
a=a.append(b)
if a is not None:
for i in a:
print(i)
li=[1,2,3]
def testcall():
c=10
func(li,c)
if __name__=='__main__':
test()
Why it is not printing the updated list
even though is I update the list in test function and then sent it, it’ll not print anything. Does anyone have any clue why the function is having this strange behavior.
If I let the "func" to only accept the one argument and sent update the list in "test" It’ll still don’t show anything.
Answers:
To answer your main concern of "why doesn’t it print anything", when you perform a = a.append(b)
, the inner a.append(b)
returns nothing, so a
is nothing. Also, a major issue exists with your code because it lacks correct indentation and you’ve misnamed your call to testcall()
as test()
. This is probably what you want.
def func(a,b):
print(a) # [1,2,3]
a.append(b)
print(a) # [1,2,3,10]
if a is not None:
for i in a:
print(i)
li=[1,2,3]
def testcall():
c=10
func(li,c)
if __name__=='__main__':
testcall()
Some experiments you can do from within IDLE:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = a.append(b)
>>> c
>>> a
[1, 2, 3, [4, 5, 6]]
>>>
def func(a,b):
a=a.append(b)
if a is not None:
for i in a:
print(i)
li=[1,2,3]
def testcall():
c=10
func(li,c)
if __name__=='__main__':
test()
Why it is not printing the updated list
even though is I update the list in test function and then sent it, it’ll not print anything. Does anyone have any clue why the function is having this strange behavior.
If I let the "func" to only accept the one argument and sent update the list in "test" It’ll still don’t show anything.
To answer your main concern of "why doesn’t it print anything", when you perform a = a.append(b)
, the inner a.append(b)
returns nothing, so a
is nothing. Also, a major issue exists with your code because it lacks correct indentation and you’ve misnamed your call to testcall()
as test()
. This is probably what you want.
def func(a,b):
print(a) # [1,2,3]
a.append(b)
print(a) # [1,2,3,10]
if a is not None:
for i in a:
print(i)
li=[1,2,3]
def testcall():
c=10
func(li,c)
if __name__=='__main__':
testcall()
Some experiments you can do from within IDLE:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = a.append(b)
>>> c
>>> a
[1, 2, 3, [4, 5, 6]]
>>>