Dima
Dima

Reputation: 517

How to create an instance of a class for each value in a list?

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?

Upvotes: 0

Views: 69

Answers (3)

Jack
Jack

Reputation: 21163

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()

Upvotes: 2

Neil
Neil

Reputation: 14313

You can use exec to accomplish your goal.

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

Upvotes: 1

Patrick
Patrick

Reputation: 131

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.

Upvotes: 0

Related Questions