0

I was thinking is there a way to take a string that is in a list and convert it to list in python? For example, I have a list: teams = ['team_one', team_two', team_three,]. How do I get three separate empty lists from it? team_one = [] team_two = [] team_three = [] Thank you!

  • 6
    Don't. Use a dictionary instead:`dic = { k: [] for k in teams}` – Błotosmętek Apr 21 '20 at 17:51
  • 1
    I invoke [X-Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you need your end user to supply the names of variables *internal* to your program? – Prune Apr 21 '20 at 18:07

3 Answers3

0

You are talking about dynamically creating variables. Ideally you should not be doing this and use typical data structures instead.

If you had to you could do something like this

    for name in teams:
        globals()[name] = 0

    for i in range(10):
        globals()['variable{}'.format(i)] = 0

For more information as to why this is a bad idea check out this link

below is a slightly easier to understand code but also still a bad idea.

>>> name = input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
Josh Zwiebel
  • 883
  • 1
  • 9
  • 30
0

This is not a good idea in common ways, but if forced, you can do:

>>> teams = ['team_one', 'team_two', 'team_three']
>>> for i in teams:
...     exec(i + ' = []')
... 
>>> team_one
[]
>>> team_two
[]
>>> team_three
[]
  • Thank you! @Naufan Rusyda Faikar. Why this is a bad idea? – Arte Bu Apr 21 '20 at 18:18
  • There are several articles that have explained about it, including [Why should exec() and eval() be avoided?](https://stackoverflow.com/q/1933451/8791891) and what has been explained by @josh-zwiebel. – Naufan Rusyda Faikar Apr 21 '20 at 18:33
-1

You can use a for loop to add to a dictionary (or create a dictionary with list comprehension, as @Blotosmetek commented). Both do the same thing.

d = {}

for item in teams:
    d[item] = []

EDIT:

In hindsight, a for loop can just be used to create the variables with no need for a dictionary.

for item in teams:
    item = []
student
  • 1
  • 1