0

For example, say I have a list:

people = ["bob", "tom", "joe"]

I'd like to make a class instance for each name.

I'm guessing there's no easy way to create variable names on the fly, like so:

for num in range(0, 3):
    person_"num" = Person(people[num])

How do I accomplish this?

Dima
  • 459
  • 1
  • 3
  • 13
  • 1
    Possible duplicate of [Using a string variable as a variable name](http://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name) – McGrady May 03 '17 at 03:08
  • Possible duplicate of [How do I create a variable number of variables?](http://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – DYZ May 03 '17 at 03:16

3 Answers3

2

As recommended in the comments using a dictionary is good for this:

people = ["bob", "tom", "joe"]
person_lookup = {}
for p in people:
    person_lookup[p] = Person(p)

or more idiomatically:

people = ["bob", "tom", "joe"]
person_lookup = {p: Person(p) for p in people}

then use like:

person_lookup["bob"].some_method_on_person()
Jack
  • 20,735
  • 11
  • 48
  • 48
1

You can use exec to accomplish your goal.

for num in range(0, 3):
    exec("person_"+str(num)+" = Person(people[num])")
Neil
  • 14,063
  • 3
  • 30
  • 51
  • Why isn't it recommended? – Dima May 03 '17 at 03:08
  • @Dima esp. in cases where you are accepting user input, malicious activity can occur. – JacobIRR May 03 '17 at 03:11
  • It's unnecessary (you can use indexed lists rather than named variables) and unsafe (if you do exec on user input, you could have potential security flaws) – Abid Hasan May 03 '17 at 03:11
  • Can you explain how to use indexed lists? This doesn't work: person[0] = Person("Joe") – Dima May 03 '17 at 03:16
  • `person[i] =...` won't work unless a list `person` has been already created with enough space for at least `i+1` items. – DYZ May 03 '17 at 03:19
0

Why not use a list of Persons instead?

persons = []
people = [ "bob", "tom", "joe" ]
for p in people:
    persons.append(Person(p))

Then you can index them by number.

Patrick
  • 121
  • 2
  • 8
  • 3
    A more Pythonic way is to use list comprehension `persons = [Person(p) for p in people]` – DYZ May 03 '17 at 03:20
  • Oh thanks, The error came from setting the object to person[0] without having defined that variable earlier. – Dima May 03 '17 at 03:23