Langfao Langfao - 1 month ago 7
Python Question

How do I make the elements in one list equal the elements of the other list with loops?

So I'm trying to define a function so that the elements of a list

elements = ['H', 'N', 'C', 'O']

equal to the elements in another list in the same positions

molarMass = [1.00794, 14.0067, 12.0107, 15.9994]


So that H = 1.00794, N = 14.0067, etc..

Edit:
trying to define a function example:
elementMolarMass(elementSymbol)

that when used will look like this
elementMolarMass('H')

and it returns the corresponding element from the first list and match with the element in the other list that is in the same position
1.00794
.
Not sure how to even begin with that.

Answer

You could bind them with dictionary comprehension

    elements = ['H', 'N', 'C', 'O']
    molarMass = [1.00794, 14.0067, 12.0107, 15.9994]

    ElementToMolar = {elements[x]:molarMass[x] for x in range(len(elements))}

    for x in ElementToMolar:
        print (x, ElementToMolar[x])

Which outputs:

    O 15.9994
    H 1.00794
    N 14.0067
    C 12.0107

Or if you want to abstract it with operations and use / interact with the data further, probably should use a class?

elements = ['H', 'N', 'C', 'O']
molarMass = [1.00794, 14.0067, 12.0107, 15.9994]

class Element(object):
    def __init__(self, Name, Mass):
        self.Name = Name
        self.Mass = Mass

    def __str__(self):
        return "{0.Name} = {0.Mass}".format(self)

H = Element("H", 1.00794)
N = Element("N", 14.0067)

print (H, N)

Which outputs: H = 1.00794 N = 14.0067