If i write
a=eval('[[0]*2]*2')
a[0][0]=1
a would become [[1,0],[1,0]]
If I write
a=eval(`[[0]*2]*2`)
a[0][0]=1
a would become [[1,0],[0,0]]
Can anyone tell me why?
>>> '[[0]*2]*2'
'[[0]*2]*2'
>>> `[[0]*2]*2`
'[[0, 0], [0, 0]]'
The first one is text, the second evaluates immediately into data structure and returns its text representation '[[0, 0], [0, 0]]'.
The problem with [[0]*2]*2 is that this evaluates to a list of references to the same object. That's why you get [[1,0],[1,0]] and not [[1,0],[0,0]].
eval('[[0]*2]*2')
This creates the result of evaluating the Python code [[0]*2]*2. Multiplying a list makes a list with several references to the original objects. The resulting list is [x, x], where each x is a list that looks like [0, 0]. Modifying one of the sublists modifies both, because they are the same object.
eval(`[[0]*2]*2`)
This creates the above (via the inner [[0]*2]*2), then creates its string representation (because of the backticks), which is [[0, 0], [0, 0]], then creates the result of evaluating that as Python code. This time, the two sublists are separate lists that each look like [0, 0], but are separate objects. Modifying one of them has no effect on the other, because they are not the same object.
BTW, using `` has been strongly discouraged for many years. You can't actually quote things with ``. It's used to create the string representation of some Python object.
`hi mom`
is a syntax error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With