This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 6 years ago.
I'm kinda new to python... So I've been strugling with a problem for a while and after doing a huge research I did not find solution so I decided to ask here :).
So the code that is explaining my problem:
test = []
solutions = []
i = 0
while i < 100:
for i in range(0, 64):
pos = random.randrange(0, 64)
test.append(pos)
solutions.append(test)
test.clear()
i += 1
So I want to add a copy of a table to another table everytime the loop goes and then clean the table named test. The problem is I don't know how to create a copy of list each time the loop goes. So I'm getting list of empty lists :(
I tried with copy.copy or copy.deepcopy but that didn't work.
That is my first question here so sorry for any "errors" also I'm not native english speaker but I hope you will be able to understand me.
You can append duplicates by calling the list constructor
solutions.append(list(test))
You can do copy the list like:
solutions.append(test[:])
And to empty it, since there is no empty method, you can just reassign it to a new empty list:
test = []
Like Zaphod mentioned, your while loop never finished, since you were never updating the value of i, plus is was being assigned in the inner for loop anyway. Why not use two nested for loops? (the underscore is just a var placeholder signifying the value is not used)
import random
test = []
solutions = []
for _ in range(0, 100):
for i in range(0, 64):
pos = random.randrange(0, 64)
test.append(pos)
solutions.append(test[:])
test = []
print solutions
if you want clean simply dont use test.clear()
use:
test = []
you should remove the test.clear(), and change <100 of while because is infinite
import random
test = []
solutions = []
i = 0
while i < 100:
for i in range(0, 64):
pos = random.randrange(0, 64)
test.append(pos)
solutions.append(test)
Related
This question already has answers here:
Why does foo.append(bar) affect all elements in a list of lists?
(3 answers)
Closed last month.
I am trying to update a list of Recorded Coordinates for a simple snake game. However, when I try to save the coordinates in the list, they all update to the most recent values.
I have tried setting the coordinates to a more global scale instead of inside a class file and making copies of the data I need, however none of these worked. A simple example of this is here:
my_list = []
run = True
var1 = [5, 50]
i = 0
while run and i <= 10:
i += 1
my_list.append(var1)
var1[0] += 1
var1[1] -= 1
print(my_list)
I am running python 3.11.0.
The problem is that each time you append var1 to my_list, you append a reference to the same object. If you subsequently change data in that object (i.e. by var1[0] += 1), then that has an effect on all elements of my_list. That's just how Python deals with lists. You can read more on that in other posts or you check out general Python documentation on lists.
A solution in your case could be to make a copy of the list var1 in each iteration, and append that copy to my_list. In that case, all elements of my_list will point to a different location in memory. This is achieved by simply calling .copy() on the list at hand:
my_list = []
run = True
var1 = [5, 50]
i = 0
while run and i <= 10:
i += 1
my_list.append(var1.copy())
var1[0] += 1
var1[1] -= 1
print(my_list)
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 1 year ago.
list = [[0,0]]
x = [0,0]
for i in range(5):
x[0] += 1
list.append(x)
expected result: [[1,0],[2,0],[3,0],[4,0],[5,0]]
actual result: [[5,0],[5,0],[5,0],[5,0],[5,0]]
I have tried several things, but none seem to work.
I am open to any suggestions, I am trying to keep "x" as a list and would prefer to stay away from doing something like
x1 = x[0]
x2 = x[1]
I think the problem is that it’s appending the list, not its contents, so it changes each time to the current value of the list(x). However, I’m really not sure what the exact problem is.
You could solve your problem by doing the following:
List=[[0,0]]
x=0
for I in range(5):
x += 1
list.append([x,0])
This question already has answers here:
Python: if element in one list, change element in other?
(3 answers)
Closed 2 years ago.
I am pretty new to python and I am trying to swap the values of some variables in my code below:
def MutationPop(LocalBestInd,clmns,VNSdata):
import random
MutPop = []
for i in range(0,VNSdata[1]):
tmpMutPop = LocalBestInd
#generation of random numbers
RandomNums = []
while len(RandomNums) < 2:
r = random.randint(0,clmns-1)
if r not in RandomNums:
RandomNums.append(r)
RandomNums = sorted(RandomNums)
#apply swap to berths
tmpMutPop[0][RandomNums[0]] = LocalBestInd[0][RandomNums[1]]
tmpMutPop[0][RandomNums[1]] = LocalBestInd[0][RandomNums[0]]
#generation of random numbers
RandomNums = []
while len(RandomNums) < 2:
r = random.randint(0,clmns-1)
if r not in RandomNums:
RandomNums.append(r)
RandomNums = sorted(RandomNums)
#apply swap to vessels
tmpMutPop[1][RandomNums[0]] = LocalBestInd[1][RandomNums[1]]
tmpMutPop[1][RandomNums[1]] = LocalBestInd[1][RandomNums[0]]
MutPop.append(tmpMutPop)
Neighborhood = MutPop
return(Neighborhood)
my problem is that I do not want to change the variable "LocalBestInd" and want to use it as a reference to generate new "tmpMutPop"s in the loop, but the code put "LocalBestInd" equal to "tmpMutPop" every time that loop is iterated. The same problem happens for other assignments (e.g., tmpMutPop[1][RandomNums[1]] = LocalBestInd[1][RandomNums[0]]) in this code.
Would you please help me to solve this problem?
Thank you
Masoud
Try this:
import copy
And change the line
tmpMutPop = LocalBestInd
to this:
tmpMutPop = copy.copy(LocalBestInd)
Depending on the structure of LocalBestInd, you may need copy.deepcopy() instead.
Here's a quote from the copy documentation that explains what's going on:
Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.
Assuming that LocalBestInd is a list, the problem, I think, is that when you're setting
tmpMutPop = LocalBestInd
in the loop, the value tmpMutPop is not a separate list but is just a reference to the list LocalBestInd, which actually contains the data. There's only one list - when you try to update the former, you're really only updating the latter.
Simple example of this works here:
>>> x = [1, 2]; y = x; y[0] = 2; print(x)
[2, 2]
What may help you here is calling .copy() on your list, e.g.:
>>> x = [1, 2]; y = x.copy(); y[0] = 2; print(x)
[1, 2]
If that doesn't work then check out the other list copying methods in this SO answer: How to clone or copy a list?
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 3 years ago.
I wrote a really simple code to create some nested lists, and I got an unexpected problem, that while loop doesn't end.
Have no idea what is wrong in it. If you have any clues, would much appreciate it)
import random
square = [0,0,0,0,0,0,0,0,0]
squares = []
def allsquares():
for i in range(9):
squares.append(square)
return squares
def autofill():
for i in range(9):
fn = random.randint(1,3)
sn = random.randint(6,8)
for s in range(fn,sn):
print('Mary Sue')
d = True
while d:
x = random.randint(0,8)
print(x)
if squares[i][x] == 0:
d = False
squares[i][x] = random.randint(1,9)
return squares
allsquares()
autofill()
print(squares[2])
Without looking too closely at your code, the issue seems to be coming from the way in which you are populating squares.
square = [0,0,0,0,0,0,0,0,0]
squares = []
def allsquares():
for i in range(9):
squares.append(square)
return squares
allsquares appends list-references to the square list. These are not independent deep-copies of your square list, but just views to the same underlying list in memory. Any change you make to ANY of your list-references will result in the same change in all other "lists" - since all you're really doing is modifying the single underlying list.
Get rid of allsquares and square, and initialize squares using a list-comprehension:
squares = [[0] * 9 for _ in range(9)]
This will result in nine independent lists. That being said, this will allow the while-loop to terminate, however, I don't know if this actually results in your desired behavior.
This question already has answers here:
Appending to list with loop
(2 answers)
Closed 3 years ago.
I am trying to create a cartesian product of the alphabet with loops. I have for loops that create the desired output but i in my while loop is never reached for some reason.
This loop is running forever in a jupyter lab notebook.
lower_az = [chr(ord('a') + i) for i in range(26)]
i=0
n=2
lst = lower_az.copy()
final_list = []
while i < n:
for let in lst:
for j in range(26):
strng = let + lower_az[j]
lst.append(strng)
i += 1
final_list.append(lst)
Unless I am missing something obvious the variable i should increment until it reaches n and stop the while loop at the desired length of strings.
You are changing the list you are iterating over. The problem is not the while-loop, it's the lst.append(strng) while iterating for let in lst.
#blue_note is correct - Python doesn't behave well when you change a list you're iterating over.
It looks like this is just a typo, though: you've got final_list all ready to receive the elements. To fix this, change:
lst.append(strng)
to
final_list.append(strng)
and drop final_list.append(lst) and your program appears to work fine.