Tuples

Spring 2026

https://www.py4e.com/lessons/tuples

https://runestone.academy/ns/books/published/py4e-int/tuples/toctree.html

https://www.keithdillon.com/index.php/python-for-data-science-spring-2026/

GitHub Classroom: https://classroom.github.com/classrooms/250035910-keithops-bds754-s26

Google CoLab: https://colab.research.google.com/notebooks/welcome.ipynb

Quick Recap of Containers¶

https://docs.python.org/3/tutorial/datastructures.html

Lists¶

mylist = list() # or []
mylist = [1,2,3,4]

Sets¶

myset = set() # or {}
myset = {1,2,3,4}

Strings¶

mystr = str() # or ''
mystr = '1234'

Dictionaries¶

mydict = dict() # or {} note similar to set
mydict = {1:'A', 2:'B', 3:11, 'hello':there}

Tuples¶

mytuple = tuple() or () # notice can't add anything
mytuple = (1,2,3,4)

Comprehensions¶

Math-style iteration through an 'iterable' (list, tuple, or on-the-fly generation)

  • Use iterators for generating sets/lists/tuples
  • Similar to mathematical set notation
  • popular in "Coding the Matrix" https://codingthematrix.com/

$L = \{i : i \in S\}$ --> literally {i for i in S} in python

In [26]:
S = {1,2,3}
L=(i for i in S)
print(L)
for i in L:
    print(i)
<generator object <genexpr> at 0x00000256545906D0>
1
2
3
In [29]:
mydict = {'X':'hello', 'Y':'goodbye'}
[key for key in mydict]
Out[29]:
['X', 'Y']
In [34]:
mydict = {'X':'hello', 'Y':'goodbye'}
dict((mydict[key], key) for key in mydict)
Out[34]:
{'hello': 'X', 'goodbye': 'Y'}

Exercise¶

Iterate over list and produce list squared

$X = \{x^2 : x \in L\}$

L=[1,1,2,3,4,4,5]