0

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 = []
6
  • 3
    When your trying to make a bunch of variables like agent_1 agent_2 it’s a sign you should be using a list instead and using agent[1] etc. Commented Apr 12, 2019 at 5:58
  • 4
    Don't do this even if you find a way. Use a 2 dimensional list instead, i.e. agent = [] before the loop and then agent[i] = [] inside, and then access to elements using agent[n][m]. Commented Apr 12, 2019 at 5:58
  • 1
    1. Python doesn't care about the name of the variable, foo =1 and baz = 1, don't matter, so it will not let you do this. 2. As many already mentioned a 2-D list is the way to do it. Commented Apr 12, 2019 at 6:02
  • @Selcuk nice idea, I wrote this but seems like something is lightly off: agent , value = [] , [] for i in range(1,10): agent.append(value) print(agent[0][2]) Commented Apr 12, 2019 at 6:32
  • @madman You can post this as a new question explaining what is wrong with it. Commented Apr 12, 2019 at 6:42

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)] = []

Comments

-2
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': []}

1 Comment

Could you add an explanation of what your code does and why it's the right solution?

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.