I would like to iterate through all elements of a matrix (in my code a list of lists) and create an independent copy of that matrix everytime, when the checked element meets a certain condition.
Every time a copy is created, I would like to change one of the elements in the copied matrix (so that the original matrix stays the same). Every copy of the matrix should get an individual name.
After that, I would like to store that copied matrix in a list.
So, for example: Consider the original Matrix is a 2x2 Matrix, containing four integers (let's say the numbers 1 to 4, as shown in the code below). Now let's loop through the matrix elements and create a copy of the matrix everytime, when the checked element is larger than 3. So we should get one copy (because only one element, the number 4, is larger than 3). In this copied matrix, I change one of the elements (e.g. let's say adding the number 10 to the element that was checked). Then I store this copied matrix in a list. My code looks like this:
matrix = [[1,2],[3,4]]
new_copies = []
counter = 0
for i in range(0,2):
for k in range(0,2):
if matrix[i][k] > 3:
exec("item%s = matrix[:]" % counter)
exec("item%s[i][k] = matrix[i][k] + 10" % counter)
exec("new_copies.append(item%s)" % counter)
counter += 1
print(matrix)
print(new_copies)
If you run this code, you will see that the copied matrix is changed correctly and also is stored in the list.
But the original matrix also is changed. Why? I only manipulate the copied versions of the matrix, which should be independent from the original, since I follow this principle:
new_matrix = original_matrix[:]