+ 1

Python array initiation with function

Hi, found this in code in a competition: a = [[0]*2]*2 a[0][0] = 5 print(a) # output: [[5, 0], [5, 0]] Can someone explain this. Since the array is initialized with only one value, why doesn't the output consist only of 5's? Why is only the outer multiplication considered a function in the array object? ---------------------------------------------- second example: https://code.sololearn.com/cEtlmmcghyy0 arr = [[0]]*3 # [[0], [0], [0]] arr[0].append(1) # [[0, 1], [0, 1], [0, 1]] arr[0][0] = 2 # [[2, 1], [2, 1], [2, 1]] arr[0] = 3 # [3, [2, 1], [2, 1]] Why does the last assignment breaks the function?

4th Mar 2018, 2:27 PM
Dick Bond
Dick Bond - avatar
1 Respuesta
0
first *2 makes two 0 elements into the first list = [0, 0], second one makes two of the first list [[0,0], [0,0]] next row makes first element of the first list a 5, it seems to handle the second one as a mirror. list iterations and handling seem to work abit weird. another thing in lists that kind of goes nuts while iterating is if you refer list element contents to another list, it will iterate both even tho youd expect it to iterate only one. ex. list1 = [1, 2 ,3] list2 = [list1, [1, 2], [1,2,3]] if you iterate through list2 it will iterate entire contents of list1 as well :D
4th Mar 2018, 2:31 PM
Markus Kaleton
Markus Kaleton - avatar