Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting values from tuples using nested for loop

I am very new to Python and taking a course on it. We were asked to take this tuple:

 students = [
      ('Anderson', 'Brian', 'junior', 123, ('FIN 365', 'MATH 223', 'CS 410')),
      ('Brown', 'Charlie', 'sophomore', 456, ('FIN 365', 'ECON 101')),
      ('Van Pelt', 'Lucy', 'junior', 789, ('FIN 365', 'MED 300', 'NUT 150', 'MED 330'))
    ]

and use a nested for loop in order to print this output:

Brian Anderson is a junior with ID=123 studying these classes:
  FIN 365
  MATH 223
  CS 410
Charlie Brown is a sophomore with ID=456 studying these classes:
  FIN 365
  ECON 101
Lucy Van Pelt is a junior with ID=789 studying these classes:
  FIN 365
  MED 300
  NUT 150
  MED 330

I was able to get the first line of each tuple just fine using this code (I know it’s sloppy):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for row in students:
    print(f'{row[1] +  " " + row[0] + " is a " + row[2] + " with ID="} {row[3]} studying these classes: ')

But I can’t figure out how to list out the classes now. Any help would be appreciated!

>Solution :

  • You can use tuple unpacking to give names to the different elements. This is nicer than using indices (e.g. row[0], row[1]). This can be done directly inside the for.
  • Using f-strings is great, but it looks weird when you still build up the total str via +. Try to just write the whole thing in one go, no +.
  • The final element (below called classes) is a tuple as well, so this can also be iterated over using for.

Below I do all of the above:

students = [
    ('Anderson', 'Brian', 'junior', 123, ('FIN 365', 'MATH 223', 'CS 410')),
    ('Brown', 'Charlie', 'sophomore', 456, ('FIN 365', 'ECON 101')),
    ('Van Pelt', 'Lucy', 'junior', 789, ('FIN 365', 'MED 300', 'NUT 150', 'MED 330'))
]

for last, first, title, ID, classes in students:
    print(f'{first} {last} is a {title} with ID={ID} studying these classes:')
    for c in classes:
        print(f'  {c}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading