WarLord
WarLord

Reputation: 33

Python change string into variable name

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

Upvotes: 2

Views: 99

Answers (1)

hugovdberg
hugovdberg

Reputation: 1631

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)

Upvotes: 5

Related Questions