🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Add/Remove Set Items

Adding and Removing Items from Sets in Python

Adding and Removing Items from Sets in Python

1. Adding Items:

# Adding a single item
fruits = {'apple', 'banana', 'orange'}
fruits.add('grape')
# Now, fruits is {'apple', 'banana', 'orange', 'grape'}

# Adding multiple items
fruits = {'apple', 'banana', 'orange'}
fruits.update({'grape', 'kiwi'})
# or
fruits |= {'grape', 'kiwi'}
# Now, fruits is {'apple', 'banana', 'orange', 'grape', 'kiwi'}

2. Removing Items:

# Removing a specific item
fruits = {'apple', 'banana', 'orange'}
fruits.remove('banana')
# Now, fruits is {'apple', 'orange'}

# Removing an item without raising an error if not present
fruits = {'apple', 'banana', 'orange'}
fruits.discard('kiwi')
# Now, fruits is {'apple', 'banana', 'orange'}

# Removing an arbitrary item
fruits = {'apple', 'banana', 'orange'}
removed_item = fruits.pop()
# Now, fruits is one element less, and removed_item contains the removed element

# Clearing all items from a set
fruits = {'apple', 'banana', 'orange'}
fruits.clear()
# Now, fruits is an empty set: set()

These methods provide a way to modify the content of sets by adding or removing items. Keep in mind that sets do not allow duplicate elements, and adding an already existing element or removing a non-existing element has no effect.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.