I am having some problems. I have lists within lists that looks something like this:
list = [['bread', 0, 5, 2], ['pasta', 2, 8, 9], ['onion', 3, 6, 12]]
So if:
list[0] = ['bread', 0, 5, 2]
Is there away I can use the first value in each list (i.e 'bread') to become the variable for that list.
What I want in the end is:
bread = ['bread', 0, 5, 2]
I am new to python so please explain things carefully or I won't understand what you are saying. Also, the list structure is the way it is set up so I can't change it, or at least, hoping not to.
1 Answer 1
You don't want to do this. Use a dictionary:
>>> lst = [['bread', 0, 5, 2], ['pasta', 2, 8, 9], ['onion', 3, 6, 12]]
>>> d = {lst[0][0] : lst[0]}
{'bread': ['bread', 0, 5, 2]}
But if you insist...
>>> locals()[lst[0][0]] = lst[0]
>>> bread
['bread', 0, 5, 2]
From the docs:
Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
Also, list
is a built-in type. Please don't name lists that.
bread = list[0]
?list
as a variable name in Python.