Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference normal quote and backquote in python

Tags:

python

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?

like image 524
user607722 Avatar asked Feb 03 '12 09:02

user607722


2 Answers

>>> '[[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]].

like image 118
eumiro Avatar answered Oct 11 '22 13:10

eumiro


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.

like image 5
Karl Knechtel Avatar answered Oct 11 '22 14:10

Karl Knechtel