0

Similar questions have been asked to mine but not exactly the same. I'm creating a natural selection/evolution simulator, with X number of creatures. I want to dynamically create and name lists of statistics about that creature with a for loop. An example of what this could look like would be:

counter = 1
for i in range(x):
    organism(counter) = []
    organism(counter).append(whatever data I want to put in)
    counter += 1

The desired output of this for loop if x = 3 would be 3 lists, titled: creature1, creature2, creature3, and containing whatever data I wanted to append in.

I know this exact thing can't be done, but is there another way to achieve the same functionality? I know about dictionaries, but you can't dynamically create variable NAMES (i.e. creature1, creature2, creature3) with those, and they aren't really the same.

Any help is greatly appreciated.

EDIT: The solution is to use a dictionary like this:

x=int(input("How many Creatures?"))

class Creature():
    def stats(a,b,c,d):
        statsls = [a,b,c,d]
        return statsls

creatures = {i: Moosh.stats(i,i+1,i+2,i+3) for i in range(x)}

This will generate x number of lists with stats in them (the stats themselves aren't relevant.

  • 3
    This won't be the answer you're looking for.... but use a dictionary (or just a list) – Nick is tired Mar 19 '20 at 14:11
  • 1
    "you can't dynamically create variable NAMES" - yes, exactly: you can't dynamically create variable names and should use dictionaries – ForceBru Mar 19 '20 at 14:11
  • Use dictionaries. There's no advantage to creating dynamic variable names, and in most cases it's impossible anyway. – Alex Hall Mar 19 '20 at 14:11
  • 2
    Has anyone mentioned that you should use a dictionary yet? – Rashid 'Lee' Ibrahim Mar 19 '20 at 14:12
  • You can dynamically create dictionary entries with whatever names (keys) and values you want (assuming keys are not repeated) – Mikhail Genkin Mar 19 '20 at 14:12
  • 1
    Actually it's very much possible to create dynamic variable names. But it's considered a bad practice, so I'll stick with the crowd. Use dictionaries! – pacholik Mar 19 '20 at 14:14
  • @pacholik Shhhh! Don't tell people that, everyone knows you use dictionaries ;p – Nick is tired Mar 19 '20 at 14:14
  • I don't understand the problem. Why is it not possible for you to create an array/list of `creatures`. Why do you need to be able to address the creatures individually like `creature1` `creature2` etc. If the creatures are created unequally you can put the logic into `class Creature`. By having a list of `creatures` you can just iterate through them nicely. – Tin Nguyen Mar 19 '20 at 14:18
  • After doing some research and experimenting, I found a way to use dictionaries for my code. Sorry for the noob question! – VlonaldTrutin Mar 19 '20 at 16:21

0 Answers0