Can't you change the contents of the list in Python function and let it be applied in the main?

Asked 2 years ago, Updated 2 years ago, 46 views

def exc(lis1,lis2):
    lis1,lis2 = lis2,lis1
    print("lis1:",lis1)
    print("lis2:",lis2)


a = [1,2,3]
b = [4,5,6]

exc(a,b)

print(a)
print(b)

When you do this, In the exc function, the a list b list comes out opposite to each other.

Print(a) and print(b) in the main show the original a list b list value again

How do I change the contents of a list in a function to be applied in the main?

You can get it if you use return, but I want to know how to do it without using return.

python list

2022-09-22 14:29

1 Answers

There are ctypes, so you can use the pointer, but...It's uncomfortable.

In [1]: import ctypes
In [2]: def p_func(p):
    ...:     ...:     p.contents.value = 10

In [3]: p_i = ctypes.c_int(5)
In [4]: pv = ctypes.pointer(p_i)
In [5]: p_func(pv)

In [6]: p_i.value
Out[7]: 10


2022-09-22 14:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.