Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a list of tuples

Tags:

python

I have a list of tuples, called gradebook, where each list element is a tuple that corresponds to a class and a grade that a student can earn. For example,

gradebook = [('Math 212', 'Linear Algebra', 'Fall 2012', 'B'),  
             ('CS 130', 'Python', 'Spring 2013', 'A')]

And so on. I would like it to print like this:

Class: Math 212.....Subject: Linear Algebra.....Term: Fall 2012.....Grade: B`  
Class: CS 130.......Subject: Computer Science...Term: Spring 2013...Grade: A`  

I would like to be able to go through each tuple in the list, and then print out each element of the tuple. How can I achieve this?

EDIT: This is what I have right now:

for aTuple in gradebook:
    print(aTuple)

Sorry, I'm very new to Python, so I don't really understand how this works.

like image 355
yiwei Avatar asked Feb 28 '13 03:02

yiwei


People also ask

How do I print a tuple in a list?

Simply pass the tuple into the print function to print tuple values. It will print the exact tuple but if you want to print it with string then convert it to string.

How do you read a list of tuples in Python?

Method 1: Using iteration (for loop) We can iterate through the entire list of tuples and get first by using the index, index-0 will give the first element in each tuple in a list. Example: Here we will get the first IE student id from the list of tuples.

How do you access a list of tuples?

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.


Video Answer


1 Answers

General format, you can iterate through a list and access the index of a tuple:

for x in gradebook:
    print x[0], x[1]

x[0] in this example will give you the first part of the tuple, and x[1] .... so on. Mess around and experiment with that format, and you should be able to do the rest on your own.

EDIT: Although some of the other answers are nicer here, in the sense that they unpack the tuples and follow the "way of Python" more closely. Like such:

a, b, c = ('a','b','c')
like image 98
eazar001 Avatar answered Sep 22 '22 10:09

eazar001