0

I need to print each element with its atomic number and weight each on a separate line, with a colon between the name and atomic number and weight, however, it prints each three times, I understand why but have no idea how to remedy it. Help

Here is the code I used:

elements = [['beryllium', 4, 9.012], ['magnesium', 12, 24.305], ['calcium', 20, 40.078], ['strontium', 38, 87.620], ['barium', 56, 137.327], ['radium', 88, 266.000]]

for x in elements:
    for i in x:
        print str(x[0]), ':', str(x[1]), str(x[2])
2
  • 1
    Why do you have the extra for i in x: line? It seems to do nothing except make the code repeat three times. Remove that, that's all. Commented Jul 16, 2014 at 16:19
  • You do not need to call str on each item that you want to print. Doing print x[0], ':', x[1], x[2] would work fine. Commented Jul 16, 2014 at 16:23

1 Answer 1

4

You are looping over the 3 nested elements; simply remove the nested for:

for x in elements:
    print str(x[0]), ':', str(x[1]), str(x[2])

You can also have Python unpack the elements into separate names; note that the explicit str() calls are not needed here as you are not concatenating the values; let print take care of converting the values to strings for you:

for name, number, weight in elements:
    print name, ':', number, weight

Next, use string formatting to get more control over the output:

for name, number, weight in elements:
    print '{:>10}: {:3d} {:7.3f}'.format(name, number, weight)

and you get nicely formatted output:

>>> for name, number, weight in elements:
...     print '{:>10}: {:3d} {:7.3f}'.format(name, number, weight)
... 
 beryllium:   4   9.012
 magnesium:  12  24.305
   calcium:  20  40.078
 strontium:  38  87.620
    barium:  56 137.327
    radium:  88 266.000
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.