8

I use eval() to assign a list to a var:

eval('mylist = [1,2,3]') 

but when I run it , I got a SyntaxError. What's wrong with it? If I cannot do assignment in the eval(), how do I assign a var in the runtime.

4
  • 1
    On a totally unrelated note, you're probably better off using either locals(), globals(), or for the really daring, a dictionary. Commented Jun 21, 2013 at 7:43
  • @Snakes and Coffee: Now I have learned these two functions. Here is my situation: I want to create a new member var in a class. How do I implement it ? Commented Jun 21, 2013 at 7:56
  • 3
    you could do setattr(<your object>,'mylist',[1,2,3]) Commented Jun 21, 2013 at 7:58
  • @SnakesandCoffee much better, <your object> would be self if this is in __init__ for example Commented Jun 21, 2013 at 8:57

1 Answer 1

13

Use exec for statements:

>>> exec 'lis = [1,2,3]'
>>> lis
[1, 2, 3]

eval works only on expressions, like 2*2,4+5 etc

eval and exec are okay if the string is coming from a known source, but don't use them if the string is coming from an unknown source(user input).

Read : Be careful with exec and eval in Python

Sign up to request clarification or add additional context in comments.

2 Comments

Not that this is exec('mylist = [1, 2, 3]') in python 3
Insert obligatory "be careful with exec, it can be dangerous" here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.