简体   繁体   中英

Pyhton 3.9 How to update a list from an imported python file

list.py

value1 = "a"
value2 = "b"
value3 = "c"

list_of_values = [value1, value2, value3]

main.py

import list

list.value1 = "d"

print(list.list_of_values)

this returns ["a","b","c"] when I want it o return ["d","b","c"], how do I update list_of_values in list.py so that when it is accessed in main.py it returns the proper values for value1, value2 and value3

Any help would be greatly appreciated.

You can use:

import list

list.list_of_values [0]= "d"

print(list.list_of_values)

Here we are updating the element of the list direct. Additionally I would suggest you to not use list as the file name as it may lead to confusion as it is already a keyword in python.

So you generally don't want to name your files after reserved keywords like list. The other comments below your post mentioning the immutability of references are also important to note.

As I mentioned in my comment, I believe what you want is:

list1.py

value1 = "a"
value2 = "b"
value3 = "c"

list_of_values = [value1, value2, value3]

main1.py

import list1

list1.list_of_values[0] = "d"

print(list1.list_of_values)

Output:

['d', 'b', 'c']

Assuming that you do not need to achieve the output by changing value1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM