Tuples

CS 65: Introduction to Computer Science I

Tuple

It's an ordered collection like a list, but it uses parentheses ( ) instead of square brackets [ ]

In [5]:
my_tuple = ("Eric",100,3.14)
print(my_tuple[0])
Eric

Except, tuples are immutable.

  • You can't change an item in a tuple
  • There are no methods like append(), insert(), pop(), or remove()
In [6]:
my_tuple[1] = 200
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-0d96e7d7f79c> in <module>
----> 1 my_tuple[1] = 200

TypeError: 'tuple' object does not support item assignment

Purpose and benefits of tuples

Tuples are typically used when you have a grouping of related data that doesn't need to change; whereas, lists are typically used when you have a collection of a bunch of the same thing.

Tuples are also

  • Faster than lists
  • Safer for things that shouldn't be changed
  • Expected for working some modules and libraries (including working with images!)
In [ ]:
student_info = ("Stu Dent",100123456,"Computer Science")

student_list = [("Stu Dent",100123456,"Computer Science"), ("Elena Schmidt",100123457,"Math"), 
                ("Krystal Harmon",100123458,"Computer Science"), ("Marcos Hopkins",100123459,"Biology"), 
                ("Terry Richardson",100123460,"Political Science")]                                                    

Tuples can also be used to return more than one thing from a function.

In [8]:
import csv

def parks_num_size(state):
    
    with open("nationalparks.csv") as npfile:
        parks_2d_list = list(csv.reader(npfile))
    
    num_parks_in_state = 0
    size_parks_in_state = 0
    
    for park in parks_2d_list:
        
        if park[1] == state:
            num_parks_in_state += 1
            size_parks_in_state += float(park[3])
    
    return (num_parks_in_state, size_parks_in_state)

parks_num_size("California")
Out[8]:
(8, 2944702.3)

Single-item tuples

You can have tuples with one thing in them, but you need to include a comma to tell Python it's a tuple and not just a parenthesized value.

In [9]:
my_val = (100) 
print(my_val, type(my_val) )
100 <class 'int'>
In [10]:
my_monuple = (100,)
print(my_monuple, type(my_monuple))
(100,) <class 'tuple'>