Python Set – Add()

◀CC++C#DartGolangJavaJavaScriptKotlinPHPPythonRRustSwiftTypeScriptUNITS▶
  • Free Android Apps
  • Learn Python - Free Android AppLearn Python
  • Python Tutorials
  • Python Basics
  • Python Hello World
  • Python Comments
  • Python Datatypes
  • Python Console Operations
  • Python Conditional Statements
  • Python Loop Statements
  • Python Enum
  • Python Operators
  • Python Strings
  • Python Functions
  • Python Builtin Functions
  • Python Try-Except
  • Python Type Conversion
  • Python Collections
  • Python Lists
  • Python Dictionary
  • Python Sets
  • Python Tuples
  • Python Advanced
  • Python Classes and Objects
  • Python Decorators
  • Python File Operations
  • Python Recursion
  • Python Global Variables
  • Python Regular Expressions
  • Python Multi-threading
  • Python Libraries
  • Python datetime
  • Python flask
  • Python json
  • Python logging
  • Python math
  • Python mysql
  • Python Matplotlib
  • Python nltk
  • Python numpy
  • Python opencv
  • Python pandas
  • Python phonenumbers
  • Python pickle
  • Python pillow
  • Python pymongo
  • Python random
  • Python requests
  • Python selenium
  • Python sqlite3
  • Python tkinter

Python Set add() method

Python Set add() method adds given element to the set.

In this tutorial, you will learn how to use Python Set add() method, with syntax and different usage scenarios, with example programs.

Syntax of Set clear()

The syntax to call add() method on a set is

set.add(element)

Parameters

Set add() method takes one parameter.

ParameterDescription
elementRequiredAny valid Python object.This object is added to the set.
Python Set add() method parameters table

Return value

add() method returns None.

Examples

1. Adding an element 'g' to Set in Python

In this example, we shall add an element to the set. The element we are adding, is not already present in the set.

Python Program

# Take a set set_1 = {'a', 'b', 'c'} # Add element to set set_1.add('g') print(set_1)

Output

{'g', 'c', 'a', 'b'}

2. Adding a duplicate element to the Set in Python

In this example, we shall pass a duplicate element, element that is already present in the set, to add() method. The resulting set should be unchanged because set can have only unique elements.

Python Program

#initialize set set_1 = {'a', 'b', 'c'} #add() method with duplicate element set_1.add('c') print(set_1)

Output

{'c', 'a', 'b'}

The resulting set is unchanged. The elements of the original set and modified set are same.

Summary

In this Python Set Tutorial, we learned how to use add() method to add elements to a set, with the help of well detailed Python programs.

Python Libraries

PythondatetimePythonflaskPythonjsonPythonloggingPythonmathPythonmysqlPythonMatplotlibPythonnltkPythonnumpyPythonopencvPythonpandasPythonphonenumbersPythonpicklePythonpillowPythonpymongoPythonrandomPythonrequestsPythonseleniumPythonsqlite3Pythontkinter

Tag » How To Add To A Set Python