Search code examples
pythonfor-loopprintingnested-loops

Using for loops with nested loops in python


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

Solution

  • 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