Tuesday, 16 June 2020

Sets in Python

Understanding Sets

Set is one of the built-in data structures or data types baked into Python. Set offers functional features which are crucial for specific purposes.

Functional Features:

Unordered: Set items are unordered i.e. items order during creation is not preserved for further.

Unique: Items in set must be unique. No two same items are allowed.

Immutable: Items in set cannot be changed, only deletion and addition of items in set is allowed.

Sets do not support indexing as they are unordered. Hence, cannot be used to access and change the item.

Sets type also support different types of data types but as their items must be immutable so they cannot have mutable types like Lists, Dictionaries.


Creating Sets in Python

Set can be created in two ways. First, Using built-in set ( ) function:

set_1 = set( )                                           // only way to create empty set

set_1 = set ( iterable  )

set_1 = set ( [1, 2, 3, 4] )                      // generates list as iterable into set


{1, 2, 3, 4}

Creating sets using set() function, takes the argument as iterable.

set_1 = set( ‘sets’ )                                // argument as iterable


{ ‘e’, ‘t’, ‘s’ }

As sets features, order is not preserved and items are unique.


Second, Using curly braces ( { } ):

set_2 = { object1, object2, …}

set_2 = { ‘sets’, ‘tuples’, ‘lists’ }


{ ‘lists’, ‘tuples’, ‘sets’ }

set_2 = { ‘sets’ }                                             // argument as object

{ ‘sets’ }

Observe the difference, using set () function argument is considered as iterable but using curly braces( {} ) they are considered as objects even they are iterable individually.

as lists are mutable objects and hence cannot be used in the set (set using curly braces { }).