TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python Set add() method with Examples

Python Set add() method with Examples on python set add() method, python set discard() method, python set pop() method, python set remove() method, python tutorial, introduction, applications etc.

<< Back to PYTHON

Python Set add() Method

Python add() method adds new element to the set. It takes a parameter, the element to add. It returns None to the caller. The method signature is given below.

Signature

add(elem)

Parameters

elem: element to be added.

Return

It returns None.

Let's see some examples of add() method to understand it's functionality.

Python Set add() Method Example 1

A simple example to add a new element in the set. It returns a modified set.

# Python set add() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.add(4) # Adding new element
# Displaying elements
print("After adding new element: \n",set)

Output:

{1, 2, 3}
After adding new element: 
 {1, 2, 3, 4}

Python Set add() Method Example 2

Adding an element which already exist will not modifiy the set. Set does not store duplicate elements. See the example below.

# Python set add() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
# Calling method
set.add(2) # Adding duplicate element
# Displaying elements
print("After adding new element: \n",set)

Output:

{1, 2, 3}
After adding new element: 
{1, 2, 3}

Python Set add() Method Example 3

Set also allows to store other datastructures like tuple, list etc. See the example below.

# Python set add() Method
# Creating a set
set = {1,2,3}
# Displaying elements
print(set)
tup = (4,5) # Creating tuple
# Calling method
set.add(tup) # Adding tuple to the set
# Displaying elements
print("After adding new element: \n",set)
dup = (2,3,4)
set.add(dup)    # Adding duplicate using tuple
print("After adding tuple: \n",set)

Output:

{1, 2, 3}
After adding new element: 
 {(4, 5), 1, 2, 3}
After adding tuple: 
 {1, 2, 3, (4, 5), (2, 3, 4)}

Next TopicPython Set




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf