Tuple¶

Ha Khanh Nguyen (hknguyen)

1. Tuple¶

• A tuple is a fixed-length, immutable sequence of Python objects.
• A tuple can contain objects of different types!
• A big difference between Python tuple and R vector!
• You can also create a tuple of tuples:
• You can convert any sequence or iterator to a tuple by invoking tuple():

2. Elements of a Tuple¶

• Elements of a tuple can be accessed with square brackets []:
• Note: In Python (unlike R), index starts at 0.
• While the objects stored in a tuple may be mutable themselves, once the tuple is created, it's not possible to modify which object is stored in each slot.
• We know e1 (string) is immutable and e2 (list) is mutable.

3. Tuple Concatenation¶

• You can concatenate tuples using the + operator to produce longer tuples:
• Note that this is NOT the same as mutate/change the original tuple!
• Multiplying a tuple by an integer, as with lists, has the effect of concatenating together that many copies of the tuple:

• Note that the objects themselves are not copied, only the references to them.

4. Unpacking Tuples¶

• If you try to assign to a tuple-like expression of variables, Python will attempt to unpack the value on the righthand side of the equals sign:
• Even sequences with nested tuples can be unpacked:
• A common use of variable unpacking is iterating over sequences of tuples or lists:
• Python also allows unpacking only a few elements at the beginning of a tuple:
• The special key here is * (not rest). In fact, you can also run the above code with a, b, *_ = values instead.

5. count()¶

• The count() function/method counts the number of occurrences of a value.

Exercise¶

Some students' information is stored in a nested tuple where each inner tuple represents a student.

For each inner tuple, the information is stored in the following format (name, age, is female?).

Unpack this tuple and store all students name in a string (separated by comma ,), and all students' ages together and count the number of female and male students (store them in female_count and male_count).

This lecture note is modified from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.