Bertelsmann Tech Scholarship Challenge, Python, Udacity

Python – Data Structures: Sets and Tuples


The simplest of the data types. The can store strings, integers and other data types.

Example of a tuple

my_tuple = ("one", "two", "three", "four")

Each value in a tuple is separated by a comma.

We cannot change what is stored in a given tuple.

Each value in the tuple has an index starting from 0. So if we do

--> two

We would use a tuple instead of a list if we don’t have a need to change the information in the tuple.


A collection of unordered unique elements. There cannot be any duplicates in the data and the data itself cannot be changed.

However, the set itself is changeable. We can add or remove items from it.

Examples of sets

# set of integers
my_set = {1, 2, 3}
->{1, 2, 3}

# set of mixed datatypes
my_set = {3.5, "Name", ("a", "b", "c")}
->{3.5, "Name", ("a", "b", "c")}

Sets are mutable. But since they are unordered, indexing has no meaning.

We cannot access or change an element of set using indexing or slicing. Set does not support it.

We can add single element using the add() method and multiple elements using the update() method.

A particular item can be removed from set using methods, discard() and remove().

The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition.

# initialize my_set
my_set = {1,3}

# add an element
# Output: {1, 2, 3}

# add multiple elements
# Output: {1, 2, 3, 4}

# discard an element
# Output: {1, 3, 5, 6}

# remove an element
# Output: {1, 3, 5}

# discard an element
# not present in my_set
# Output: {1, 3, 5}

Similarly, we can remove and return an item using the pop() method.

Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.

We can also remove all items from a set using clear().


This is from Lesson 22:  Data Types and Operators Videos 25 – 28

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s