An Intro to
Programming
with Python

Fall 2006
course
navigation

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)
Answer (from http://www.oreilly.com/catalog/lpython/chapter/ch09.html, "Common Tasks in Python") :
# 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.
Jumping way beyond where we are in class, if you wanted Python to just 'do the right thing', you could define something like this, which tries to use eval(), and if an error occurs, uses exec instead. See http://mail.python.org/pipermail/python-list/2001-September/063323.html for a discussion.
>>> 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 >>>
http://cs.marlboro.edu/ courses/ fall2006/python/ notes/ oct_4
last modified Wednesday October 4 2006 12:52 pm EDT