Friday, December 27, 2024
Google search engine
HomeLanguagesset add() in python

set add() in python

The Python set add() method adds a given element to a set if the element is not present in the set in Python.

Syntax of Set add()

Syntax: set.add( elem )

Parameters:

  • elem: The element that needs to be added to a set.

Python Set add() Method Examples

Before going to the example we are assuming the time complexity of the set.add() function is O(1) because the set is implemented using a hash table.

  • Add Element to an Empty set
  • Add a new element to a Python set
  • Add element in a set that already exists
  • Adding any iterable to a set

Add Element to an Empty set

It is used to add a new element to the empty set.

Python3




GEEK = set()
GEEK.add('s')
print("Letters are:", GEEK)
 
# adding 'e' again
GEEK.add('e')
print("Letters are:", GEEK)
# adding 's' again
GEEK.add('s')
print("Letters are:", GEEK)


Output

Letters are: {'s'}
Letters are: {'e', 's'}
Letters are: {'e', 's'}

Add a new element to a Python set

It is used to add a new element to the set if it is not existing in a set.

Python3




# set of letters
GEEK = {'g', 'e', 'k'}
 
# adding 's'
GEEK.add('s')
print("Letters are:", GEEK)
 
# adding 's' again
GEEK.add('s')
print("Letters are:", GEEK)


Output:

Letters are: {'e', 's', 'g', 'k'}
Letters are: {'e', 's', 'g', 'k'}

Add element in a set that already exists

It is used to add an existing element to the set if it is existing in the Python set and check if it gets added or not.

Python3




# set of letters
GEEK = {6, 0, 4}
 
# adding 1
GEEK.add(1)
print('Letters are:', GEEK)
 
# adding 0
GEEK.add(0)
print('Letters are:', GEEK)


Output:

Letters are: {0, 1, 4, 6}
Letters are: {0, 1, 4, 6}

Adding any iterable to a set

We can add any Python iterable to a set using Python add or Python update function, if we try to add a list using the add function we get an unhashable Type error.

Python3




# Python code to demonstrate addition of tuple to a set.
s = {'g', 'e', 'e', 'k', 's'}
t = ('f', 'o')
l = ['a', 'e']
 
# adding tuple t to set s.
s.add(t)
 
# adding list l to set s.
s.update(l)
 
print(s)


Output :

{'a', 'g', 'k', 'e', ('f', 'o'), 's'}

RELATED ARTICLES

Most Popular

Recent Comments