'python - modifying an item inside an array using a function

I am new to python. Can someone please explain to me how this works in python? How to change the value of item in the main function?

def calc(arr = []):
    index = 0
    for item in arr:
        item = item + 1
        arr[index] = item
        index += 1


if __name__ == '__main__':
    item = 1
    calc([item])
    print("item is => ", item)


Solution 1:[1]

you can do with the global keyword in python which allows us to use a non-global variable as global if we get an error like 'UnboundLocalError: local variable '' referenced before assignment' in that case we also use the global keyword I have done the same code with proper assignment in the below image

enter image description here

as you have declared variable in the wrong place because that would only be accessible inside the if block only so you have to place the variable at the upper level and what will happen if I don't use the global keyword see the below image

enter image description here

you can see the difference

and if you like my answer please follow me and upvote my answer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SHYAM SHEEL