What are they?

A Set is an unordered, mutable collection that will not retain duplicate values.

A Tuple is an ordered, immutable, collection that can accept duplicates.

How are they created?


three basic ways –

Using the set( ) function: s = set( )

Converting a list to a set: s = set(list_name) or s = set( [obj 1, obj 2, obj 3, …] )

Braces notation: s = {‘a’, ‘b’, 1, 2, 2}

Note: You cannot have nested lists when converting a list to a set


Using parenthesis: t = ( )

by assignment using parenthesis: t = (1,2,3,4,5), or without: t = 1,2,3,4,5

Note: to create a tuple with a single entry, you must include a comma. Here is an example: t2 = ( 1, ) This is a rule of the language, a syntactic quirk of Python. If you do this: t2 = ( 1 ), and use the type function: type(t2), it will return an ‘int’ object type, not the expected tuple.

When to use them?

Set[s]: Whenever you need to create a collection of distinct values, and/or apply mathematical set theory to those values ( intersection, union, difference, etc. ). Or, if you need to convert an existing list containing duplicate values, you can specify it in the set function.

Tuple[s]: Used mostly for values that need to remain constant.

Methods to use:

You can use the dir( ) function to find all methods and “dunders” contained for the type.

dir(set) | dir(tuple)

Since Tuples are immutable, they do not contain many of the common methods to append, clear, add, etc. In fact, only two exist: Index and Count

Example Code:

Here are some code examples from my Jupyter Notebook.  I’ve included some basic examples for both Sets and Tuples.  *Click on the image to view a larger picture.



In this blog entry I’ve included the definition of a Set and a Tuple.  I have reviewed their usage, creation,  and shown some example code using both.

My next blog will focus on using Python with PyODBC to connect to an instance of SQL Server 2016, perform a SELECT statement on an existing table.  I’ll then use a For Each loop to review the data returned.  It’s very simple to do, and only requires a minimum of coding to perform.

Knowledge is Power!


Python Tuples:  https://docs.python.org/3/library/stdtypes.html#tuple

Python Sets:  https://docs.python.org/3/library/stdtypes.html#set

Jupyter Notebook:  http://jupyter.org/