Sakshi

Posted on

# Settling with SETS - Python

Hello geeks!

After tuple and lists, lets see sets.

## 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.

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

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

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}
print(len(set))
``````

### FOCUS HERE

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

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.

``````
``````

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"
print(hash(string))
``````

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.

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.

``````for i in set:
print(i)
``````

## 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)
print(theSet)
``````

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

there's a way

But one element from the list, at a time

``````print('theSet ', theSet)
theList1 = [1,2]
for i in theList1:
print('theSet now', theSet)
``````

## 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])
set1.update({2,3},"n")
set1.update("hehehe","abc")
print("\nSet after Addition of elements using Update: ")
print(set1)
``````

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.

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 :)

msc2020

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]
``````

Sakshi

thats nice trick! thanks for sharing :)