oct 4
list copy
Asked in class:
"How do I copy a list?"
# This doesn't work.
a = [1,2,3] # a list
b = a # the same list
id(b)
id(a)
# You can use the slice notation :
c = a[:] # make a new list from a sublist of a
# or use the copy module (which also has a 'deepcopy' function for complicated data structures)
from copy import copy
c = copy(a)
eval
I was getting confused in class about what
'eval' does in python. Here was my confusion:
>>> eval('1+2*3')
7
>>> eval('a=3')
# SyntaxError: invalid syntax
The first line was what I expected eval() to do: take some python code, and execute it.
The second line surprized me: isn't 'a=3' valid python code?
Turns out that eval() only understands "expressions", which loosely speaking is the right hand of an assignment statement. There's a built-in, exec, which can handle more elaborate python code. Like 'print', it's not a function, it's a built-in part of the langage; therefore, it doesn't use parens.
>>> exec 'a=3'
>>> a
3
However, exec never returns a value; eval() does.
>>> def eval_or_exec(str):
... try:
... result = eval(str)
... except SyntaxError:
... exec str
... result = None
... return result
...
>>> eval_or_exec('5*5')
25
>>> eval_or_exec('print "hi"')
hi
>>>