DEV Community

Cover image for Settling with SETS - Python

Posted on

Settling with SETS - Python

Hello geeks!

After tuple and lists, lets see sets.

Python Unleashed 09

How to create set

There are two ways to define a set in Python. You can use the set() function, which takes in a iterable and converts the iterable to a set.

Image description

Showing you the first way of creating set, when you have elements ready with you

set = {"this", "is", "a", "set",12,True}

Image description

See what error we get here. And what's unhashable type.

To get better understanding of how set is related to hash, lets see important properties of set.

  • Unordered -> you will not see items in order, unchangeable order (Ascending/descending/sorted)

  • No duplicate elements -> calculate length of set with two duplicate values, it will return the length as one. Hence we can prove the unique element only rule for set.

set = {1,2,1}
Enter fullscreen mode Exit fullscreen mode


Set is mutable object, which contains only immutable elements
List, Set, Dictionaries are mutable.
Tuple, String, Integer are immutable.

  • A set cannot have mutable elements like a list or dictionary, as it is immutable. (as seen in above snapshot, we get error on adding list to set)

  • A set itself may be modified, but the elements contained in the set must be of an immutable type - adding more clarity.

  • Set does not support indexing and slicing.


Hashable means hash is associated with each element in set.
For now, consider hash as combination of random alphabets, numbers or hexadecimal number. So any value can be converted to hash by making it to go through a process, that process is called as hash function. When a text/value is passed to hash function, it produces hash of that. If two values have same hash they are considered same. This method used for calculating hash can not be used to get original text again, only hash values are matched. We have so many hashing algorithms also. Hope you got good idea of what hashable means. If not, feel free to google.

Python sets can only include hashable objects.

That means that they can include immutable objects because all immutable objects are hashable and they can include mutable objects that are hashable. So, some examples that you’ve probably seen of immutable objects are tuples, strings, integers, and Booleans.

Enter fullscreen mode Exit fullscreen mode

This is because these objects cannot be modified after they were created.

You can also imagine if you can call hash() on your object and it doesn’t error, then it’s hashable. Lists and dictionaries are unhashable because we cannot call the hash() method on them.

Immutable vs Hashable

Immutable objects are a type of object that cannot be modified after they were created. Hashable objects, on the other hand, are a type of object that you can call hash() on.

So if you go into the Python interpreter and type hash, open parenthesis, and then put your object in there, close , and hit Enter and it does not error, then that means that your object is hashable.

All immutable objects are hashable, but not all hashable objects are immutable. That’s just a rule, so anytime you see some example immutable object, you know for a fact that it’s hashable, but there are some cases where there are hashable objects that you actually can mutate. Python sets can only include hashable objects.

Let’s look at strings. We can create a string like this, and we can see that strings are indeed immutable. Let’s try to actually mutate it and see that this will error.

string = "string type"
Enter fullscreen mode Exit fullscreen mode

We get hash on running above code.

Hash remains same for the entire lifetime of object, so this is the reason why immutable objects have hash. Hash is value which is generated once for an object, and then adding more items to it or editing it may affect existing hash value.

So if we try to add a character to the end or change the first character to another character, both of those will error. That’s because strings are immutable and do not actually have any methods that allow us to mutate them.

The same goes for integers. We can create an integer, and we can’t add a number to an integer or add an integer to the end of itself and actually change what this 10 is.

Once the 10 is created, we cannot change it. We can, however, reassign x—but that doesn’t actually change the 10.

So if we want to add list to set, we would use set() method.
Otherwise, when we know what elements to add we can explicitly create set, as long as elements are immutable.

Image description

To iterate or loop over a set, use the same syntax as you would a list or tuple, or any iterable for that matter. But note, you cannot slice or index sets because they’re not ordered, so that doesn’t really make sense to slice some of them or get the zeroth index or something like that. So, here’s an example. We have a set with {'foo', 'bar', 'baz'}.

We try to index. It errors, because it says 'set' is not subscriptable.

Image description

for i in set:
Enter fullscreen mode Exit fullscreen mode

Set is mutable object, which contains immutable types only.

  1. Create set using curly brackers.

set = { 1,2,3}

  1. Create set using set() method
theList = [1, 2, 3, 4, 2, 3, 1]
theSet = set(theList)
Enter fullscreen mode Exit fullscreen mode

What if we want to add list (mutable) in existing set?

there's a way

Using add() method

But one element from the list, at a time

add() method

print('theSet ', theSet)
theList1 = [1,2]
for i in theList1:
print('theSet now', theSet)
Enter fullscreen mode Exit fullscreen mode

Image description

Update method

For the addition of two or more elements Update() method is used. The update() method accepts lists, strings, tuples as well as other sets as its arguments. In all of these cases, duplicate elements are avoided.

See how duplicate elements are avoided

set1 = set([4, 5, (6, 7)]) 
set1.update([10, 11]) 
print("\nSet after Addition of elements using Update: ") 
Enter fullscreen mode Exit fullscreen mode

Image description

See how one letter is added to avoid duplicacy.

We'll see accessing, deletion, popping and all other remaining things about SET in next blog to finallt settle with Sets in python.

Image description

This data structure has really annoyed me in past, this is the reason I wanted to settle set concept this time.

Hope you also got good understanding of what is mutable and what is not and when it is not.

Thanks for reading this long blog

good day :)

Top comments (2)

msc2020 profile image

Thanks! Post good for study set theory and tricks as remove duplicates from a list:

# remove duplicates of [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
print(list(set([1, 2, 3, 4, 5, 5, 4, 3, 2, 1])))
# [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode
bellatrix profile image

thats nice trick! thanks for sharing :)