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):
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 thefor. - Using f-strings is great, but it looks weird when you still build up the total
strvia+. Try to just write the whole thing in one go, no+. - The final element (below called
classes) is atupleas well, so this can also be iterated over usingfor.
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}')