0

this is my code

def change_w(w):
    for item in range(len(w)):
        w[item] += random.randint(-5, 5)
    return w

the function change_w takes each number in a list and changes it by a random amount between -5 and 5. the parameter w is the list you put into the function and it returns w but changed.

o_list = [100, 100, 100, 100]
all_list = []
for i in range(3):
    x = change_w(o_list)
    print(x)
    all_list.append(x)
print(all_list)

the point of this program is to make a list with 3 different lists inside of it that are slightly off from the o_list

I want all_list to look something like [[102, 101, 98, 97], [99, 100, 103, 103], [100, 101, 96, 98]] but when I print all_list it prints [[100, 101, 99, 96], [100, 101, 99, 96], [100, 101, 99, 96]] (they are all the same list and I want it to be 3 different lists) I know my function is working because when I print out x in the for loop it is different every time but when it appends x to all_list it just appends the same one 3 times instead of 3 different ones.

  • `all_list.append(x)` doesn't make a copy of `x`. So you're putting multiple references to the same list in `all_list`, and then you're modifying that list. – Barmar Jun 07 '22 at 17:27
  • Use `all_list.append(x.copy())` – Barmar Jun 07 '22 at 17:27
  • To add on to that answer, you can also modify your `change_w` function to return a new list rather than modifying the list `x` that gets passed in to it – gloo Jun 07 '22 at 17:29

0 Answers0