IKH

In Build Function

add(x)

  • Adds item x to the set

Example

Python
s={10,20,30}
s.add(40)
print(s)

Output

PowerShell
{40, 10, 20, 30}

update(x,y,z)

  • To add multiple items to the set.
  • Arguments are not individual elements and these are Iterable objects like List, range etc.
  • All elements present in the given Iterable objects will be added to the set.

Example

Python
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5))
print(s)

Output

PowerShell
{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}

Question

What is the difference between add() and update() functions in set?

Answer

  • We can use add() to add individual item to the Set, where as we can use update() function to add multiple items to Set.
  • add() function can take only one argument where as update() function can take any number of arguments but all arguments should be iterable objects.

copy()

  • Returns copy of the set.
  • It is cloned object.

Example

Python
s={10,20,30}
s1=s.copy()
print(s1)

Output

PowerShell
{10, 20, 30}

pop()

  • It removes and returns some random element from the set.

Example

Python
s={40,10,30,20}
print(s)
print(s.pop())
print(s)

Output

PowerShell
{40, 10, 20, 30}
40
{10, 20, 30}

remove(x)

  • It removes specified element from the set.
  • If the specified element not present in the set then we will get KeyError.

Example

Python
s={40,10,30,20}
s.remove(30)
print(s)
s.remove(50)

Output

PowerShell
{40, 10, 20}
KeyError: 50

discard(x)

  • It removes the specified element from the set.
  • If the specified element not present in the set then we won’t get any error.

Example

Python
s={10,20,30}
s.discard(10)
print(s)
s.discard(50)
print(s)

Output

PowerShell
{20, 30}
{20, 30}

Questions

  • What is the difference between remove() and discard() functions in set?
  • Explain differences between pop(),remove() and discard() functions in set?

clear()

  • To remove all elements from the set.

Example

Python
s={10,20,30}
print(s)
s.clear()
print(s)

Output

PowerShell
{10, 20, 30}
set()

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error