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
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 :)
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).
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.
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.
listfor a variable name, it shadows the built-in