Create Python Sets and add elements

Python Set

In this post, we are going to all about Create Python Sets and add elements. What is Python Sets (Examples)

1. What is Python Sets

“Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.” Python Docs

Important Points for Set

  • The SET is an unordered and unique collection data type in python. It is unordered means, it does not remember the insertion order, Therefore elements can’t be accessed by the index and we can’t perform slicing on set.
  • All elements in the set are immutable data types (not changeable) those include (string, tuple, integer, tuple, float).
  • But Set itself is mutable, meaning we can change the Set by adding or removing elements from it.
  • It does not contain immutable collection as elements(list, dictionaries).

2. How to create a set in Python?

There are three ways to create Python SET

  • Create Python set using Set() function:
  • Create Python set using the literal syntax({})
  • Create Python set Using Set comprehension

Important Note :

We can’t create an empty Set by using Curly bracket({}) because curly brackets are used to create a dictionary. If we create a set using Curly brackets ({}), it will be a dictionary. We always use the Set() function to create an empty set

Let us understand with an example.

Example: If we create Set by Using curly brackets

#empty set using Curly bracket

empty_set = {}

#empty set using Curly bracket

first_set = set()

print('type :',type(empty_set))
print('type :',type(first_set))

Output

type : <class 'dict'>
type : <class 'set'>

2.1 Create Python set Using Set() function:

It is a built-in function to create a set. It takes a single parameter iterable.

Syntax

set(iterable)

Iterable: It is optional parameter and it can be a sequence (tuple, list, string) or dictionary that will be converted into set elements.

Return value

  • A empty set(), if not parameter passed.
  • A set of elements from the iterable, if iterable passed as an argument.

Create set from a List,Tuple,String iterable,Dictionary

#----set from list with mixed data types----

mixed_set = set(['alice', 'john', 'rack',1,2])
print('set from mixed data-type =\n',mixed_set,'\n')

#-----set from a string ----

str_set = set('rack')
print('set from string = \n ',str_set,'\n')

#------set from a tuple -------

tuple_set  = set(('name','jack','age',25,'sub','Math'))
print('set from tuple =\n',tuple_set)

#-----set  from a dictionary-----

dict_set  = set({'A':65,'B':67,'C':68})
print('\nset from Dictionary =\n',tuple_set)

Output

In the resulting output, when we are converting list,string,tuple into SET, it does not preserve the order. Because it is an unordered collection.

set from mixed data-type =
 {'alice', 2, 1, 'rack', 'john'} 

set from string = 
  {'c', 'r', 'k', 'a'} 

set from tuple =
 {'sub', 'age', 'Math', 'jack', 25, 'name'}

set from Dictionary =
 {'C', 'B', 'A'}

2.2 Create Python set Using literal Syntax({})

This is another way to create a set in python. We pass all the elements separated by a comma.

Syntax

{element1,element2...............elementn}

Create Python Set using literal Syntax

In this code example, we are using the {} bracket to create a set. If any of element is duplicate while creating the SET it gets removed because SET only contain unique element.

#set from  mixed data types, duplicate elements

mixed_set = {'alice', 'john', 'rack',1,2.5,2.5}
print('set from mixed data-type =',mixed_set)


#set from  tuples

tuple_set = {('alice', 'john', 'rack'),1,2,2.5,2.5}
print('set from mixed data-type =',tuple_set)

#end here

Output

set from mixed data-type = {1, 'alice', 2.5, 'john', 'rack'}

set from mixed data-type = {1, 2, 2.5, ('alice', 'john', 'rack')}

2.3 Create Python set using Set comprehension

It create a new set from a existing iterable or set.

Syntax for this

{expression for element in iterable if condition}
  • Expression: Optional parameter, applies to each element of a set that satisfies the condition.
  • Element: It is required, the variable of the input set.
  • iterable : required parameter,The input iterable(list,tuple,dict,string) to create set.
  • Condition: optional parameter, condition apply on each element of a set.

Return Value

It return a set from all the elements of iterable separated by comma(,)

Let us understand with example

Create a set from list,dict,tuple,string and set

Here we are using a SET comprehension to create a set from list,dict,tuple,string and set.

my_set = {1,2,3,4,5}

#Create set from the set using set comprehension

my_set = {element*element for element in my_set }
print('set from set =',my_set)


#Create  set from a list using set comprehension

my_list = [6,7,8,9,10]

list_to_set = {element*element for element in my_list if element<=9 }

print('set from set =',list_to_set)


#Create  set from tuple using set comprehension


my_tuple = (1,7,14,11,8)

tup_to_set = {element*element for element in my_tuple if element<=8 }

print('set from tuple =',tup_to_set)



#Create  set from Dict using set compreshesion

my_dict = {'A':1,'B':7,'C':14}

Dict_to_set = {element for element in my_dict}
print('set from dict =',Dict_to_set)


#Create  set from string using set compreshesion

string_to_set = {element for element in 'Morning' }
print('set from string =',string_to_set)

Output

set from set = {1, 4, 9, 16, 25}
set from list = {1, 4, 9, 16, 25}
set from tuple = {64, 1, 49}
set from dict = {'C', 'A', 'B'}
set from string = {'g', 'M', 'n', 'r', 'i', 'o'}

3. Understand Mutable datatypes can not be Set element with example

Set does not contain mutual data types (a list, dictionary, Set) as its elements. Let us understand with an example what will happen if we try to add them in Set.

A Set as Set element

The set does not contain a mutable data type as its element,if we are using SET as its element then it will throw an error.

#Set can not be as a set element

mixed_set = {'alice', 'john', 'rack',{1,2.5,2.5}}
print('set from mixed data-type =',mixed_set)


Output

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    mixed_set = {'alice', 'john', 'rack',{1,2.5,2.5}}
TypeError: unhashable type: 'set'

A List as Set element

The set does not contain a mutable data type as its element,if we are using LIST as its element then it throw an error.

#list as a set element

list_as_set_element = {12,13,{'a':23,'b':24}}
print('set from mixed data-type =',list_as_set_element)

Output

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    list_as_set_elem = {12,13,[23,24]}
TypeError: unhashable type: 'list'

3 How to add elements to Python Sets

There are two ways to add elements in set

  • Add() method :Add single element using set add() method.
  • Update() method :Add Mutiple elemnts using set update() method

3.1 Python Set Add() method

The add() method of the Python set is used to add a single element in the set. If the element is already existing in the set then it will not add the element.

Syntax

set.add(element)

Element: It is the required parameter, represents the element we are adding in SET.

Return Value

It will return none(nothing)

Code Example Adding Element Using Add() Method

Here we are adding two-element ‘Good’ and 1.’Good’ will be added to the set. But 1 already exists. So it will be not be added in SET.

first_set = {'evening',1}

#adding element using add() method

first_set.add('Good')

#adding elemnt that is already exist in set
first_set.add(1)

print('set after adding element :',first_set)

Output

set after adding element :
 {1, 'evening', 'Good'}

Python Set Update() Method

To add multiple elements at once we use update() method.It takes iterable as a argument. We can add single or multiple iterable in set using Update() method.

Syntax

set.update(iterable1....iterablen)

iterable: This is a required parameter, it can be one or multiple iterable these include(string, list, dictionary, tuple). If we are passing single iterable or multiple iterable elements of iterable will add to SET.

Return Value

It will return none(nothing)

Code Example :Adding single list to set using update() method

update() method can add single or multiply iterable to set. Here we are adding a single iterable(list)

list_sub = ['eng','math','CHEM']
first_set = {'evening',1}

#adding list to Set using update() method

first_set.update(list_sub)

print('set after adding element :\n',first_set)

Output

set after adding element :
 {1, 'eng', 'math', 'CHEM', 'evening'}

Code Example: Adding Multiple iterable List,Tuple,Dictionary using Update()

update() method can add single or multiply iterable to set. Here we are adding multiple iterable List, Tuple, Dictionary.

Important Note: If we adding a dictionary in set,only keys of dictionary will be added to the set.

list_sub = ['eng','math','CHEM']
mytuple = (80,90,40)
mydict = {'A':65,'B':67,'C':68}
first_set = {'evening',1}

#adding list,tuple,dict to Set using update() method

first_set.update(list_sub,mytuple,mydict)

print('set after adding element :\n',first_set)

Output

set after adding element :
 {1, 'evening', 'CHEM', 40, 'A', 'B', 'eng', 80, 'C', 90, 'math'}