-1

I have a list say for example , a =["1","2"]

i want , c =1 and d = 2 . I can do c = a[0] , d = a[1] which will give me the required output , but if the list contents are dynamic ? How to store each elements in a list in a variable.

Thanks

Gautham
  • 3
  • 3
  • You can't create variables on the fly like that. In order to do what you want, you need another list, just to hold those values.. But then why not just keep and use the original list? –  Jun 28 '16 at 16:48
  • Yes, i could achieve what i was trying to do with the original list itself. Thanks :) – Gautham Jun 28 '16 at 16:51
  • Possible duplicate of [How do I do variable variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) – Łukasz Rogalski Jun 28 '16 at 16:58
  • `c, d = seq` is a shorthand unpacking form, but it won't help you with 'dynamic' list length. – Łukasz Rogalski Jun 28 '16 at 17:00

1 Answers1

0

One way (bad practice, but works):

x = ord('a')
list = ["1", "2"]
for i in list:
    exec('%s="%s"' % (chr(x), i))
    x+=1

But I would personally go this way:

from collections import namedtuple

list = ["1", "2"]
names = ["a", "b"]
d = dict(zip(names,list))
obj = namedtuple('X', d.keys())(*d.values())

Then, you can use obj.a, obj.b, etc.

Derlin
  • 9,572
  • 2
  • 32
  • 53