Pampel
Pampel

Reputation: 21

How to select a name of a new list from existing string?

I'm quite new to python and I'm not able to solve this. In a loop, I have a list with some numbers and a string with the desired name of the list. I want to create a new list identical to the existing list a named it according to the name from the string.

values = [1,2,3] name='Ehu'

What I need is a new list named 'Ehu' containing the same items as the list values, but I don't know how to select a name of the new list from existing string.

Thanks

Upvotes: 1

Views: 177

Answers (2)

Nabeel Ahmed
Nabeel Ahmed

Reputation: 19252

Can be done using globals:

>>> g = globals()
>>> name = 'Ehu'
>>> g['{}'.format(name)] = [1, 2, 3]
>>> Ehu 
[1, 2, 3]

Upvotes: 1

Mark Tolonen
Mark Tolonen

Reputation: 177715

While you can do what you ask:

>>> globals()['Ehu'] = [1,2,3]
>>> Ehu
[1, 2, 3]

or for local variables:

>>> def f():
...   f.__dict__['Ehu'] = [1,2,3]
...   print(Ehu)
...
>>> f()
[1, 2, 3]

That is a bad practice. A better solution as @Moses commented:

>>> list_names = {}
>>> list_names['Ehu'] = [1,2,3]
>>> print(list_names['Ehu'])
[1, 2, 3]

Upvotes: 0

Related Questions