1
def function_b(b_list, high_num):
    c_list = [0,0,0,0,0,0,0]
    i = 0
    for num in b_list:
        if num> high_num:
            c_list[i] = num
        i = i +1
    b_list = c_list
def main():
    b_list=[1,3,6,4,1,2,8]
    high_num=4
    function_b(b_list, high_num)
    print(b_list)
main()

Can anyone explain why this wouldn't print [0,0,6,0,0,0,8]? I thought that since lists were mutable objects that if we assign the parameter b_list =c_list in function_b, it would change b_list found within main. Why does this have no affect on the argument b_list we insert into function_b?

  • 5
    `b_list` becomes local to function as soon as you have an assignment to it, which is destroyed after the function scope is over. – Austin Mar 05 '20 at 06:44
  • Does this answer your question? [Python modifying list within function](https://stackoverflow.com/questions/27264526/python-modifying-list-within-function) – Tayyab Mar 05 '20 at 06:46
  • your function `function_b` is not returning anything and whatever Austin explained is also true. – Ashu007 Mar 05 '20 at 06:52

2 Answers2

3

use return from function_b

def function_b(b_list, high_num):
    c_list = [0,0,0,0,0,0,0]
    i = 0
    for num in b_list:
        if num> high_num:
            c_list[i] = num
        i = i +1
    return c_list

def main():
    b_list=[1,3,6,4,1,2,8]
    high_num=4
    b_list = function_b(b_list, high_num)
    print(b_list)
main()
Lambo
  • 1,094
  • 11
  • 18
2

Because in your function_b,b_list is a local variable.And it can not affect the local variable in the main function

Use global variable,like this:

def function_b(high_num):
    global b_list
    c_list = [0,0,0,0,0,0,0]
    i = 0
    for num in b_list:
        if num> high_num:
            c_list[i] = num
        i = i +1
    b_list = c_list
def main():
    global b_list
    b_list=[1,3,6,4,1,2,8]
    high_num=4
    function_b(high_num)
    print(b_list)
main()

Or use the return value:

def function_b(b_list, high_num):
    c_list = [0,0,0,0,0,0,0]
    i = 0
    for num in b_list:
        if num> high_num:
            c_list[i] = num
        i = i +1
    return c_list
def main():
    b_list=[1,3,6,4,1,2,8]
    high_num=4
    b_list = function_b(b_list, high_num)
    print(b_list)
main()
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49