2

So I have a list of strings MyList=['ID_0','ID_1','ID_2',.....] from which I used an exec function to create a empty list with elements as names i.e. each I have empty lists ID_0=[] and so on. I now want to create a for loop where I take each list by name and append elements to it like

for i in range(len(MyList)):
     *magic*
     ID_0.append(i)

where with each loop it uses to next list i.e. ID_1,ID_2.... and so on

I wanted to take each string in MyList and change it into a variable name. Like take 'ID_0' and change it into say ID_0 (which is a empty list as defined earlier) and then make a list BigList=[ID_0,ID_1,ID_2,.....] so that I can just call each list from BgList in my for loop but I dont know how

3
  • You want this: docs.python.org/3/c-api/reflection.html. Reflection is problematic to describe unless you already know what it's called, :) Commented Jul 30, 2021 at 13:04
  • Well, just about everything so far screams “this is a terrible approach”, but as a nudge, why can’t you keep using exec? Commented Jul 30, 2021 at 13:04
  • 1
    It looks like you rather need a dictionary with ID_0, ID_1 as keys and set their values to said list. Commented Jul 30, 2021 at 13:05

1 Answer 1

5

A safer way instead of using exec might be to construct a dictionary, so you can safely refer to each list by its ID:

MyList=['ID_0','ID_1','ID_2']

lists = {}
for i, list_id in enumerate(MyList):
    lists[list_id] = [i]

Note that using enumerate is more pythonic than range(len(MyList)). It returns tuples of (index, item).

Alternatively, you could also use defaultdict, which constructs a new item in the dictionary the first time it is referenced:

from collections import defaultdict

lists = defaultdict(list)
for i, list_id in enumerate(MyList):
    lists[list_id].append(i)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.