Issue
I am trying to understand indexing in a list. I try:
x= [1,2,3,[4]]
x[0]=[34]
x[3][0]=95
which gives
[1, 2, 3, [95]]
but why is it not:
[34 2, 3, [95]]
? Edit: apologies my code was:
x= [1,2,3,[4]]
y=list(x)
x[0]=[34]
x[3][0]=95
print (y)
Which gives the results I stated.
Solution
In this case, I believe python list mutability doing strange things.
When you call
y = list(x)
It copies each element in the list x over to the list y.
This means it avoids mutability in the first dimension, but because the third element is copied normally under the hood, and it is a list, it remains mutable.
You can find out a bit more in the docs (https://docs.python.org/3/library/stdtypes.html#list)
Also, as others have pointed out, you are setting
x[0] = [34]
Which sets the first element of x to a list, not a number so x would actually be
[ [34], 2, 3, [95] ]
Answered By - not a tshirt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.