How to call and change global list variables inside Python functions

In python, for global digital variables, string variables, and list variables, the function can only be called inside the function, but its value cannot be changed; however, for dictionary variables, the value of the global dictionary variable can be changed inside the function!

The modification of global variables inside the function

Verification scheme

# 全局变量
x = 50
str = 'str'
dt = {
    
    '1': 'one'}
li = []

# 自定义函数
def func(x, str, dt, li):
    print('局部变量x={}, str={}, dt={}, li={}'.format(x, str, dt, li))
    x = 2
    str = 'string'
    dt['1'] = '1'
    li = [1]
    print('局部变量x={}, str={}, dt={}, li={}'.format(x, str, dt, li))

# 调用函数,验证全局变量的变化
func(x, str, dt, li)
print('全局常数变量x=', x)
print('全局字符串变量str=', str)
print('全局字典变量dt=', dt)
print('全局列表变量li=', li)

The result shows

Insert picture description here
Through the analysis of the results, it can be concluded that, except for the dictionary variables, nothing else has changed!


In the actual development process, you may encounter the need to change the value of the global list variable inside the function, how to achieve it?

How to modify global list variables inside a function

It's actually very simple, we just needBorrow dictionary structureYou can achieve this function!

Give a simple chestnut

# 全局字典变量,value为列表
dict_list = {
    
    1: []}

# 自定义函数
def func(li):
    dict_list[1] = li

# 调用函数,验证结果
func([1, 2])
print(dict_list)
func([3, 4])
print(dict_list)

The result shows

Insert picture description here
The example is very simple, but it can explain the problem very well, and it has fully realized the demand!

Guess you like

Origin blog.csdn.net/WU2629409421perfect/article/details/115276954