0

I have a list, list = ['foo','bar'] and now i want to create a string from each item.

Each string is named as the item and has the value of the item

foo = 'foo' bar = 'bar'

Thanks to all, i will use a dict instead

2
  • 7
    don't use list for a variable name, it shadows the built-in Commented Jan 22, 2010 at 10:35
  • What's the point? What higher-level-of-abstraction are you trying to solve? Commented Jan 22, 2010 at 10:43

5 Answers 5

9

Don't do that. Use a dict instead.

strings = dict((x, x) for x in L)
Sign up to request clarification or add additional context in comments.

Comments

3

Ignacio Vazquez-Abrams is right, using a dict is better. But if you insist on having them available as variables, you can always do this:

strings = dict((x, x) for x in L)
locals().update(strings)

PS: Edan Maor's version with exec has a security issue. It won't handle ["foo", "';__import__('os').system('rm -rf ~');'"], for example :)

Comments

1

Try:

>>> l = ["foo", "bar"]
>>> for item in l:
    exec("%s = '%s'" % (item, item))

Note: Why do you need this? Are you sure this is the best way to do what you want to do? I ask because this is usually not such a great idea.

Security Warning: As pointed out by Attila Oláh, running arbitrary code using "exec" is a very bad idea. Only use this if you're in control of the string in the list (and they're not, for example, input from the user).

Comments

0

In spite of their names, variables in Python should in fact not themselves be variable. If you have data you want to associate with a 'name', you should be using a dict instead:

data = {}
for s in ['foo', 'bar']:
    data[s] = s

It is sometimes(!) possible to modify locals() to introduce new variables, but since you would have no sensible way of referring to them (as you don't know their name when you write the code) there's really no value in it. All it does is make your code a lot slower and much harder to understand.

Comments

0

Take a look at http://docs.python.org/library/functions.html#setattr

You should be able to do something along the lines of

for x in list:
    setattr(object, x, x)

Assuming object is whatever object you wanted to add the attributes to.

Comments

Your Answer

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