-4

I've found a way to create new lists with this method where p is an integer variable:

L=""
L= "player" + str(p) + "=[]"
exec(L)

However I don't know how to refer back to these list using a variable. when p=5, the list player5=[] is created. But I can't refer back to it as (playerp), since p doesn't get converted to 5 like a variable. How can I refer back to the list playerp?

p=10
print(player10) 
M= "player" + str(p)
print(M)
print(M is player10)

output:
[]
player10
False

right now M is the string "playerp", how do I make it so that M will refer to the list playerp instead of the string "playerp"(player10 in the example)?

  • 4
    This is a job for a list of lists, not `exec`. – user2357112 Apr 22 '23 at 14:15
  • 1
    Build a dictionary of players instead – JonSG Apr 22 '23 at 14:24
  • 1
    Does this help you: https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – ndc85430 Apr 22 '23 at 14:40
  • 1
    I’d like to find whoever it is that goes around teaching new programmers about `exec()` and have them tried as a war criminal. It’s almost always the absolute worst tool in the toolbox and inevitably causes a lot of pain for the beginner until someone rescues them. – Samwise Apr 22 '23 at 14:56

1 Answers1

0

As it was commented using Dictionaries is a good way to create dynamic variables, here is a sample code:

a={}
k=0
while k<10:
    key = "player"+str(k)
    value = list(a.get("player"+str(k-1),[0]))+list([k])
    a[key] = value 
    k += 1
print (a)

This link might be helpful: How can you dynamically create variables?

  • the lists I'm using are objects in a class function. Is it possible to take individual list from a dictionary and assign them to a class function? – Issac Chan Apr 22 '23 at 16:57
  • Do you mean you want to pass them to a class method? if you could provide an example, it would be so helpful. – shabnam aboulghasem Apr 22 '23 at 17:17