I'm trying to set area
to List
except if a wanted to change area
, List
would stay the same. So I did a for loop that would get each element from List
and append it to area but that seems to almost be working, like if I was missing a step. Can somebody explain to me why it is not working? Preferably don't send code because I want to code it myself followed with an explanation, but if you really need to its fine.
List = [[1, 1, 1, 2, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [2, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1]]
area = []
for Map_list in range(len(List)):
area.append([])
for Map_index in List[Map_list]:
area[Map_list].append(List[Map_list][Map_index])
For comparison:
print(f'area: {area}')
print(f'List: {List}')
1 Answer 1
The for Map_list
loop sets Map_list
successively to the index of each list in List
so those sublists can be used as sources for copying.
The for Map_index in List[Map_list]:
goes through the values, not the indexes of the elements of the sublist. But the statement
area[Map_list].append(List[Map_list][Map_index])
uses Map_index
as an index, so it doesn't have the desired effect. It uses data from the sublist as an index on the sublist.
To get the desired effect of changes to area
having no effect on List
, you should use the deepcopy
function from the copy
module of the standard library. This also means you don't need your nested for-loops any more.
The suggested solution of area = [*List]
solves the problem of making a list that looks the same, but does not satisfy the requirement that changes to List
should not affect area
. Demonstration:
>>> list1 = [[1]]
>>> list2 = [*list1]
>>> list1
[[1]]
>>> list2
[[1]]
>>> list1[0][0] = 99
>>> list1
[[99]]
>>> list2
[[99]]
print(f'area: {area}')
to be the same as this outputprint(f'List: {List}')
But instead, the outputs are differentarea = [*List]
what you want? By the way, it's nice to follow PEP8 styling when coding in Python. Try to use Snake Case when declaring variables. (list_
instead ofList
,map_list
instead ofMap_List
and so on)List
were mutable objects (other lists). You are right, by doing just that, it would not word for that case.