What is add method in sets | How to use add method of sets.

Definition:

This method is used to add an element inside a set at any random location, also if the element is already present it does not add the element nor does it throw an error.

Syntax:

set.add(item)

This method takes the item (element) as an argument.

Working:

What is add method in sets

How to use add method of sets

Code:

  1. We have taken a set of named any_name and passed some values to it.
  2. We have used add() method to it and passed mango as an argument.
  3. We have printed the set.

Output:

  1. We can see Mango inside set at a random location.

Interview Questions:

  • Why we cannot add an element inside the set at the desired location?

Set is a collection data type that is unordered and unindexed, therefore we cannot add an element at the desired location.

  • What is the difference between the insert() method of the list and add() method of the set?

Insert() method in list is used to add an element inside list at the desired location, whereas add() method in set is used to add an element at a random location. (More interview questions.)

Quick Topics:

Waqar Khan

Hello, everyone, I am Waqar Khan. I have done my B.tech in Computer Science. I love to write about Computer Informational blogs. Before write I did proper research on it. Hope you like our blogs. Thank you.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *