1

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.

asked Jun 26, 2013 at 1:48
3
  • umm... bread = list[0]? Commented Jun 26, 2013 at 1:49
  • 2
    Broken record I know, but don't use list as a variable name in Python. Commented Jun 26, 2013 at 1:49
  • possible duplicate of Python - Use a variable as a list name Commented Aug 27, 2013 at 20:16

1 Answer 1

4

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.

answered Jun 26, 2013 at 1:50
2
  • I havn't I was just using it as an example Commented Jun 26, 2013 at 1:56
  • @Danrex: Don't do that either! Commented Jun 26, 2013 at 3:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.