0

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)

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
zacdawg
  • 35
  • 5

1 Answers1

1

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.

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Thank you so much! We dont recognize the "data in zip" syntax but we'll try looking it up :-) – zacdawg Oct 06 '15 at 12:47
  • However, we didn't get this to work.. We want to name the objects by their atom name, so that we can easily reach them. What we want is something like: Ag = Atom(atom_name="Ag", atom_weight="23") but to do that for all the elements in a loop so we dont have to write them out individually.. Is there any way around that? :) – zacdawg Oct 06 '15 at 13:06
  • 1
    @zacdawg that's totally different to what you asked for. You should put them in a dictionary, not a list, mapping name to `Atom` instance; look up *"dictionary comprehension"* and you can make minor tweaks to what I've given you. Then you can easily access e.g. `atoms['Ag']` to get the object. – jonrsharpe Oct 06 '15 at 13:08