Python insert to set

Python: How to add or append values to a set ?

In this article we will discuss ways to add single or multiple elements to a set in python.

Add a single element to the set

Set in python provides a member function to append a single element to the set i.e.

It accepts an element as an argument and if that element is not already present in the set, then it adds that to the set. It returns nothing i.e. None. We can use this to add a single value to the set. Let’s understand this with an example,

Adding a value to the set using add() function,

# Initialize a set sample_set = # Add a single element in set sample_set.add(15) print(sample_set)

As 15 was not present in the set, so add() function appended that to the set.

Frequently Asked:

Adding a duplicate element to the set

As set contains only unique elements, so if try to add an element that already exist in the set, then it will have no effect. For example,

sample_set = # If element is already present the add() function will not do anything sample_set.add("Hello") print(sample_set)

As 15 was already present the set, so add() function did nothing with the set.

Adding immutable objects to the set using add() function

As Sets can only contain immutable elements, therefore we can add int, strings, bytes, frozen sets, tuples, or any other object that is immutable. For example, we can add a tuple to the set using add function,

sample_set = # Add a tuple in set sample_set.add((10, 20)) print(sample_set)

Tuple is an immutable object; therefore, it can be added to a set. Whereas list in python is a mutable object, so we cannot add a list to the python using add() function. If you try to pass a list object to the add() function, then it will give error. For example,

Читайте также:  Python async def это

Adding a mutable object like list to the set will raise TypeError

sample_set = # Pass a list to add() will raise Error sample_set.add([21, 31])
TypeError: unhashable type: 'list'

So, we can use the set.add() function to add a single element to the set. What if we want to add multiple elements to the set in one line ?

Adding multiple elements to the set

Set in python provides another function update() to add the elements to the set i.e.

It expects a single or multiple iterable sequences as arguments and appends all the elements in these iterable sequences to the set. It returns nothing i.e. None. We are going to use this update() function to add multiple value to the set in a single line,

Adding multiple values to the set using update() function

Now we want to add 3 more numbers in the set i.e. 10, 20 and 30. Let’s see how to do that,

# Add multiple elements in set by passing them as a tuple sample_set.update((10, 20, 30)) print(sample_set)

We encapsulated all three elements in a tuple and passed that tuple as an argument to the update() function. Which iterated over all the elements in tuple and added them to the set one by one. Instead of passing a tuple, we can pass a list too i.e.

sample_set = # Add multiple elements in set by passing them in list sample_set.update(['a', 22, 23]) print(sample_set)

update() function will iterated over all the elements in passed list and add them to the set one by one.

Adding elements from multiple sequences to the set

In update() function we can pass multiple iterable sequences and it will add all the elements from all the sequences to the set. Let’s understand by an example,

Suppose we have some elements in different iterable sequences like,

list_1 = ['a', 22, 23] list_2 = [33, 34, 35] sampe_tuple = (31, 32)

Now we want to add all the elements in above two lists and a tuple to the set. We can do that using update() function,

sample_set = # Add multiple elements from different sequences to the set sample_set.update(list_1, sampe_tuple , list_2) print(sample_set)

We passed both the lists and the tuple to the update() function. It iterated over all of them and added all elements in them to the set.

Читайте также:  Java manager for android

Let see some more example of update() function,

Adding dictionary keys to the set

student_dict = sample_set = set() sample_set.update(student_dict) print(sample_set)

If we pass a dictionary to the update() function of set, then it will try to convert dictionary object to an iterable sequence. Dictionary will be implicitly converted to sequence of keys and update() function will add all the keys in the dictionary to the set.

Adding dictionary values to the set

student_dict = sample_set = set() sample_set.update(student_dict.values()) print(sample_set)

We passed a sequence of all values of the dictionary object to the update(). Which added them to the set. As set contains only unique elements, so now it contains only unique values of the dictionary. So, this is how we can add single or multiple elements in the set using add() or update() function.

The complete example is as follows,

def main(): # Initialize a set sample_set = print('Original Set:') print(sample_set) print('**** Add a single element to the set ****') # Add a single element in set sample_set.add(15) print('Set contents: ') print(sample_set) print('** Adding a duplicate element to the set **') sample_set = # If element is already present the add() function will not do anything sample_set.add("Hello") print('Set contents: ') print(sample_set) print('** Adding an immutable objects to the set **') sample_set = # Add a tuple in set sample_set.add((10, 20)) print('Set contents: ') print(sample_set) print('Adding a mutable object like list to the set will raise Error') # Can not pass a list object (mutable) to the add() function of set # sample_set.add([21, 31]) print('*** Adding multiple elements to the set ***') sample_set = # Add multiple elements in set by passing them as a tuple sample_set.update((10, 20, 30)) print('Set contents: ') print(sample_set) sample_set = # Add multiple elements in set by passing them in list sample_set.update(['a', 22, 23]) print('Set contents: ') print(sample_set) print('*** Adding elements from multiple sequences to the set ***') sample_set = list_1 = ['a', 22, 23] list_2 = [33, 34, 35] sampe_tuple = (31, 32) # Add multiple elements from different sequences to the set sample_set.update(list_1, sampe_tuple , list_2) print('Set contents: ') print(sample_set) print('*** Adding dictionary keys to the set ***') student_dict = sample_set = set() sample_set.update(student_dict) print(sample_set) print('*** Adding dictionary values to the set ***') sample_set = set() sample_set.update(student_dict.values()) print(sample_set) if __name__ == '__main__': main()

Original Set: **** Add a single element to the set **** Set contents: ** Adding a duplicate element to the set ** Set contents: ** Adding an immutable objects to the set ** Set contents: Adding a mutable object like list to the set will raise Error *** Adding multiple elements to the set *** Set contents: Set contents: *** Adding elements from multiple sequences to the set *** Set contents: *** Adding dictionary keys to the set *** *** Adding dictionary values to the set ***

Читайте также:  Length of integer python

Источник

Python — Add Set Items

Once a set is created, you cannot change its items, but you can add new items.

To add one item to a set use the add() method.

Example

Add an item to a set, using the add() method:

Add Sets

To add items from another set into the current set, use the update() method.

Example

Add elements from tropical into thisset :

Add Any Iterable

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).

Example

Add elements of a list to at set:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью