Sets – Python

Hello Techies!!!

We have learned three ways to store data till now – lists, tuples and dictionaries.

Today, we will learn about a different type of collection called sets.

What are sets? What is its use?

A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets. It can’t have duplicate elements.

Let’s make a set of colors :

colors = {“red”, “green”, “yellow”, “blue”, “black”, “white”}

This is how you write a set in python. We can say that we have a set of colors which is named ‘colors’.

Curly brackets { } tells us that colors is of set type.

we can also define a mixed data type set:

mixed_set = [“red”, 1, 12.4, “yellow”, “white”]

DEALING WITH SET:

ACCESS, CHANGE AND ITERATE ELEMENT FROM SET:

Let’s break down the statements in above image,

We can directly declare a set using curly braces.

Another way to do the same thing is to pass elements as arguments in set( ) constructor which in turn will initialize and create a set.

Since, sets are unindexed, we can’t access elements present at a certain index.

The way to access element is to iterate through the set using a for loop.

we are taking each color and assigning it to variable ‘color’ and printing it on the console.

When we tried to access the element just like elements in a list. We got an error – “set doesn’t support indexing”.

LENGTH OF SET, CHECKING IF ITEM EXISTS IN SET, ADDING, DELETING AN ELEMENT :

Here, we used a bunch of built-in functions,

len() – To find the length of the set

add() – To add element to the set

update() – To add multiple elements to the set

pop() – To remove random element from the set

remove() – To remove a mentioned element.

discard() – To remove a mentioned element.

clear() – To clear all the elements from the set

del – Keyword to delete the set all together from memory.

So, this is all about set. Stay calm and Keep coding !!

See you guys in next tutorial. Have a great day!!

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.