Tuples and Lists of Tuples
Often we have data that contains several pieces of information rather than just one. For example, a student's data may contain both their name and gpa. A…
Tuples as records
Often we have data that contains several pieces of information rather than just one. For example, a student's data may contain both their name and gpa. A variable containing information about a car may contain its make, model and year.Tuples are a list-like datatype that is used as records, containing a collection of fields.
They can also be defined without any brackets at all:
What tuples can do
Like lists, tuples have a length and individual elements can be extracted using square-bracket indexing. Slicing is also supported. Unlike lists, however, tuples are immutable: a tuple cannot be modified!Tuple unpacking
Rather than accessing tuple data using indices like above, we usually will use tuple unpacking to unpack a tuple into meaningful variables.List of tuples
We can form a list of tuples to store a collection of items, each of which consists of more than one piece of information. For example, a list of students where each student contains a name and a gpa.Here's an example of a for loop that uses tuple unpacking.
The loop variable is TWO names, so each tuple is unpacked as the loop reaches it. Without unpacking you would be writing student[1] throughout and hoping you remembered which field that was.