1

I'm attempting to modifying the temp list and store the temp list in the possible list but I need to have list1 unchanged. When I ran this through Python, my temp list has not changed so I'm wondering where this has gone wrong.

list1 = [['1', '1', '1'],
     ['0', '0', '0'],
     ['2', '2', '2']]

temp = list1
possible = []

for i in range(len(temp)-1):
    if(temp[i][0] == 1):
            if(temp[i+1][0] == 0):
                    temp[i+1][0] == 1

possible = possible + temp
temp = list1

print(possible)
Judy Li
  • 13
  • 2

1 Answers1

0

For copying the array of list1 to temp since, list1 is 2D array, as suggested by others we can use deepcopy. Refer to this link here.. Alternatively, it can be done using list comprehension as well as shown here.

The array has string as element, so the conditional statements if(temp[i][0] == 1) and if(temp[i+1][0] == 0) can be replaced by if(temp[i][0] == '1') and if(temp[i+1][0] == '0'). And as mentioned above in the comments temp[i+1][0] == 1 has to be replaced by temp[i+1][0] = 1. You can try following:

from copy import deepcopy

list1 = [['1', '1', '1'],
         ['0', '0', '0'],
         ['2', '2', '2']]

# copying element from list1
temp = deepcopy(list1)
possible = []
for i in range(len(temp)-1):
    if(temp[i][0] == '1'):
        if(temp[i+1][0] == '0'):
            temp[i+1][0] = '1'


possible = possible + temp

print('Contents of possible: ', possible)
print('Contents of list1: ', list1)
print('Contents of temp: ', temp)
Community
  • 1
  • 1
niraj
  • 17,498
  • 4
  • 33
  • 48