Reputation: 329
I am having trouble understanding lists:
mList = []
def func1(mList):
mList.append("1")
return
func1()
print mList
As I understand it because a list is mutable, if I edit it in a function, the main list will also be edited. In a program I am working on this is happening with one list which I am using as a "save file", however, a second list which I am using as a "value_blacklist" is not being saved after it is edited/added to.
I included the problem part of the actual code I am having issues with if it's of any help.
def func04(feedback, test_list, value_blacklist, upper_limit=6):
if value_blacklist == []:
value_blacklist = blacklist_gen(length)
import random
new_list = []
for index in list(range(0, len(feedback))):
if feedback[index] == 0: #This value is correct, leave it
new_list.append(test_list[index])
elif feedback[index] == 2:
value_blacklist = full_blacklist(test_list[index], value_blacklist)
new_list.append(0)
elif feedback[index] == 1:
value_blacklist[index].append(test_list[index])
new_list.append(0)
for index in list(range(0, len(feedback))):
if new_list[index] == 0:
new_list[index] = pick_new(index, value_blacklist, upper_limit)
return new_list
next_guess = lambda: func04(feedback(), save_game[-1], value_blacklist, save_game[0])
Thanks for any help, I'm really confused by this.
Upvotes: 1
Views: 51
Reputation: 304393
Whereever you are saying
value_blacklist = ...
You are rebinding value_blacklist
to a new (list) object. If you instead say
value_blacklist[:] = ...
You will replace the contents of the list without rebinding it.
Ask lots of questions until you really really understand this. It's very important to "get" it.
Upvotes: 2
Reputation: 239623
When you use =
operator in a function, you are not modifying the existing object. Right hand side of the expression creates a new list and returns a reference to it and that reference is assigned to value_blacklist
.
value_blacklist = blacklist_gen(length)
...
value_blacklist = full_blacklist(test_list[index], value_blacklist)
These are the places where you create new local lists and referring them with value_blacklist
. That's why value_blacklist
doesn't reflect the changes. You can confirm this by printing the id
of value_blacklist
after the assignment statements and at the beginning of the function.
Upvotes: 1