Add items to Python sets

Sets are the collection of items that are unordered in nature. Python supports the set function and we can define a set by using a curly bracket. Here we are going to see how to add items to sets in Python.

Methods to add items to Python set

  1. Using ‘set.add()’ method:
    This is an inbuilt method through which we can add single item or a tuple into a set lets see an example below :
    Syntax = set_name.add(item_value or tuple)

    fruit_set = {'orange','apple','mango'}
    fruit_set.add('pineapple')
    print(fruit_set)
    Output:
    {'pineapple', 'apple', 'orange', 'mango'}

    i)Adding tuple:

    fruit_set1 = {'orange','apple','mango'}
    tuple2= ('grapes','strawberry','pineapple')
    fruit_set1.add(tuple2)
    print(fruit_set1)
    Output:
    {('grapes', 'strawberry', 'pineapple'), 'apple', 'orange', 'mango'}

    So we can see that tuple has successfully been added into the set. this is how we add elements or tuples using the .add function
    Note: According to Sets properties this will not add the item which is already present in the set.

  2. Using ‘set.update’ method:
    This method will add multiple items to the set.
    Syntax: set_name.update(item_values)
    Let’s see an example :

    fruits= {'orange','apple','mango'}
    fruits.update(['grapes','strawberry','pineapple'])
    print(fruits)
    Output:
    {'strawberry', 'orange', 'mango', 'pineapple', 'grapes', 'apple'}

    Thus you can see that we added multiple items to the set successfully.
    These were the simple and basics approach to add items to a Python set.

Also read:

Leave a Reply

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