0

how did the other list change?

ok so i was analysing this and was wondering why there are 2 ones in the list of list of zeros created... x = [[0]*2]*2 x[0][0] = 1 print(x) this prints [[1,0],[1,0]]

21st Feb 2022, 2:33 AM
Jamari McFarlane
Jamari McFarlane - avatar
2 Answers
+ 2
x = [ [ 0 ] * 2 ] * 2 print( f'The list {x} contains {len( x )} elements\n' ) print( '''ID of the elements are similar Meaning they all refer the same object''' ) for i in range( len( x ) ): print( f'ID of element {i} : {id( x[ i ] )}' ) print( '\nThus modification of either one also affects the other' ) x[ 0 ][ 0 ] = 1 print( x )
21st Feb 2022, 3:46 AM
Ipang
+ 2
When you create a nested list in this fashion, you're duplicating the values held within the list. When the values are mutable object types, such as a list itself, the identity is the actual value, so it is essentially copying the ID of the mutable type. Similar to a pointer value in other languages. So the nested lists are pointing to the same list. This is why a change to any of them will result in a change to all of them, as they are all the same object, not just a copy of the object(s) held by them. Use this instead to avoid the issue; x = [[0] * 2 for _ in range(2)]
21st Feb 2022, 3:47 AM
ChaoticDawg
ChaoticDawg - avatar