set add() in python
The set add() method adds a given element to a set if the element is not present in the set.
Syntax:
set.add(elem) The add() method doesn't add an element to the set if it's already present in it otherwise it will get added to the set. Parameters: add() takes single parameter(elem) which needs to be added in the set. Returns: The add() method doesn't return any value.
# set of letters GEEK = {'g', 'e', 'k'} # adding 's' GEEK.add('s') print('Letters are:', GEEK) # adding 's' again GEEK.add('s') print('Letters are:', GEEK) |
chevron_right
filter_none
Output:
('Letters are:', set(['k', 'e', 's', 'g']))
('Letters are:', set(['k', 'e', 's', 'g'])
Application:
It is used to add a new element to the set.
# set of letters GEEK = {6, 0, 4} # adding 1 GEEK.add(1) print('Letters are:', GEEK) # adding 0 GEEK.add(0) print('Letters are:', GEEK) |
chevron_right
filter_none
Output:
('Letters are:', set([0, 1, 4, 6]))
('Letters are:', set([0, 1, 4, 6]))
Adding tuple to a set:
# Python code to demonstrate addition of tuple to a set. s = {'g', 'e', 'e', 'k', 's'} t = ('f', 'o') # adding tuple t to set s. s.add(t) print(s) |
chevron_right
filter_none
Output :
{'k', 's', 'e', 'g', ('f', 'o')}
Recommended Posts:
- Python - Read blob object in python using wand library
- Reading Python File-Like Objects from C | Python
- Python | Convert list to Python array
- MySQL-Connector-Python module in Python
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Python | PRAW - Python Reddit API Wrapper
- Python | Merge Python key values to list
- Python | Add Logging to a Python Script
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- Python if else
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

