Reputation: 35
We have a problem in our program creating several objects in a loop. We're reading a list of all the elements in the periodic table and their respective atom weights from a text file. We want to create an individual object for each atom with the atom weight and the atom name as attributes. How would we easiest go about doing this?
So far, what we've come up with is this: We've created one list with all the atom names, and one with their weights. And then we tried making a loop to create multiple objects without having to create them one by one individually so we tried this:
for i in range(len(name_list)):
name_list[i] = Atom(atom_name=name_list[i], atom_weight=weight_list[i])
(Our class is named Atom
and has the attributes atom_name
and atom_weight
)
Upvotes: 0
Views: 184
Reputation: 121975
I think what you want is:
name_list = [Atom(*data) for data in zip(name_list, weight_list)]
If this syntax is unfamiliar, see Python for-in loop preceded by a variable and What does ** (double star) and * (star) do for parameters? If your class only accepts keyword arguments, you can switch to:
name_list = [Atom(atom_name=name, atom_weight=weight)
for name, weight in zip(name_list, weight_list)]
For more information on zip
, see the docs.
Upvotes: 1