madman
madman

Reputation: 153

defining multiple variables to an empty list in a loop

I am trying to create and assign 10 variables, only differenciated by their index, all as empty lists within a for loop.

The ideal output would be to have agent_1 = [], agent_2 = [], agent_n = []

I know I could write this all out but thought I should be able to create a simple loop. The main issue is assigning the empty list over each iteration

for i in range(1,10):
    agent_ + i = []

Upvotes: 0

Views: 951

Answers (3)

prashant
prashant

Reputation: 3318

Why don't you use dict object with keys equal to agent_i.

dic = {}
for i in range(1,10):
    dic["agent_" + str(i)] = []

// access the dic directly and iterating purpose also just iterate through the dictionary.
print dic["agent_1"]
# iteration over the dictionary
for key,value in dic.items():
    print key,value

Here is the link to code snippet

Upvotes: 3

Amitkumar Karnik
Amitkumar Karnik

Reputation: 931

a = {} 
for i in xrange(10):
    ab = "{}_{}".format("agent", i)
    a[ab] = []

print a
#OP 
{'agent_0': [], 'agent_1': [], 'agent_2': [], 'agent_3': [], 'agent_4': [], 'agent_5': [], 'agent_6': [], 'agent_7': [], 'agent_8': [], 'agent_9': []}

Upvotes: -2

dpkp
dpkp

Reputation: 1459

This is a horrible idea. I will let the code speak for itself:

n = 10
for i in range(n):
    globals()['agent_%d' % (i + 1)] = []

Upvotes: 0

Related Questions