Python - Native Data Structure: Sets

In our series to learn "Python for Data Science", we will discuss on "Sets in Python". In the previous blog, we have discussed on Lists and Tuples.
Lists and Tuples are ordered sequence of data elements. Sets in Python are un-ordered collection of elements and these elements have to unique.

Create a set

A set can be created with curly brackets - { and }.

s = {1,2,4,6}
s1={'a','b','f','d'}

s
{1, 2, 4, 6}

s1

{'a', 'b', 'd', 'f'}

We can also use 'set' function built in. In this we will give input list of items and you will be converted to set.

s2 =set([2,3,6,7])

s2
{2, 3, 6, 7}

Change a set in Python

We can add element/s to an existing set using add method.

s2
# current elements
{2, 3, 6, 7}
# add element to a set -s2
s2.add(13)
# Now see the elements in s2
s2

{2, 3, 6, 7, 13}

We can remove elements from a set using remove method

colors = {'Red','Green','Orange', 'Blue','Black','White'}
# remove 'Orange' element from colors set
colors.remove('Orange')
# view elements now
colors
{'Black', 'Blue', 'Green', 'Red', 'White'}

Basic Scenarios

Scenario 1: We have to create a set which stores squares of integer numbers between 1 and 10

# define empty set
squares=set()
# run loop for 1 to 10
for i in range(1,11):
    # add elements
    squares.add(i*i)

squares
{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}

Scenario 2: We have a list of cities and we want to get unique values, we can convert the list to set and get the unique list of cities. A set will always have unique values as elements.

cities=['New Orleans','Brighton','Bridgeport','Anchorage','Hamilton','Ashland',
'Chicago','San Jose','Sioux Falls','Phoenix','Mc Minnville','Aston','San Jose',
'New Orleans','Brighton','Bridgeport','Anchorage','Hamilton','Ashland',]
cities_unique=set(cities)

cities_unique
{'Anchorage',
 'Ashland',
 'Aston',
 'Bridgeport',
 'Brighton',
 'Chicago',
 'Hamilton',
 'Mc Minnville',
 'New Orleans',
 'Phoenix',
 'San Jose',
 'Sioux Falls'}

Leave a Comment