BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python Set add() Method with examples

By Chaitanya Singh | Filed Under: Python Tutorial

Python Set add() method is used to add an element to a Set. Since Set doesn’t allow duplicates, if you try to add an already existing element to a Set, it won’t do anything.

Set add() Method Syntax

set.add(item)

Here item is the element that we want to add to Set.

Set add() method Example

In the following example we have a Set myset and we are adding an element to the Set myset using add() method.

# Set add() method example

myset = {1, 2, "hello", 5, "bye"}

# displaying set before adding any element
print(myset)

#adding an element to a the Set myset
myset.add("BeginnersBook")

# displaying set after adding an element
print(myset)

Output:
Python add() method example

Example 2: Adding a tuple to a Set using add() method

In the following example, we have a Set myset and a tuple t1 and we are adding the tuple t1 to the Set myset. Similar to the elements, if we try to add an already existing tuple to a set then it won’t add it and it won’t raise any error.

# A Set
myset = {1, 2, "hi"}

# A tuple
t1 = (10, 20, "hello")

# displaying set before adding the tuple
print(myset)

#adding the tuple t1 to the set myset
myset.add(t1)

# displaying set after adding the tuple t1
print(myset)

Output:
Python add() method example - adding tuple

Leave a Reply Cancel reply

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

Python Tutorial

Introduction

  • Python Tutorial
  • Python Introduction
  • Install Python
  • PyCharm IDE Installation
  • Python in PyCharm
  • Python Comments
  • Python Variables
  • Python Keywords & Identifiers
  • Python data types

Flow Control

  • Python If
  • Python if..else
  • Python if..elif..else
  • Python Nested If
  • Python for loop
  • Python while loop
  • Python break
  • Python continue
  • Python pass

Python Functions

  • Python Functions
  • Python Recursion

Python Datatypes

  • Python Numbers
  • Python List
  • Python Strings
  • Python Tuple
  • Python Dictionary
  • Python Set

Python OOPs

  • Python OOP
  • Python Class & Object
  • Python Constructors

Python Examples

  • Python Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap