Introduction Python Set Add() Method with Examples

Introduction Python Set Add() Method with Examples

The set add() method adds a given element to a set. If the element is already present, it doesn't add any element.

Python set add() is an inbuilt function that is used to add an element to any set. The set add() method adds a given item to a set if the element is not present in the set. If the element is already present in that set, it does not add that element because, as we know, the set does not contain any duplicate value in it.

Python set add()

The syntax of set add() method is:

set.add(element)

Here, an element is the value that is to be added to the set.

Parameters

The add(0 method takes a single parameter:

  • elem - the element that is added to the set

Return Value

The set() method does not return any value or anything. It just adds the given value if it is not present in that set.

Set add() method Example

Example 1: Add an element to a set


# set of vowels
vowels = {'a', 'e', 'i', 'u'}

# adding 'o'
vowels.add('o')
print('Vowels are:', vowels)

# adding 'a' again
vowels.add('a')
print('Vowels are:', vowels)

Output:

Vowels are: {'a', 'i', 'o', 'u', 'e'}
Vowels are: {'a', 'i', 'o', 'u', 'e'}

Note: Order of the vowels can be different.

Example 2: Add tuple to a set


# set of vowels
vowels = {'a', 'e', 'u'}

# a tuple ('i', 'o')
tup = ('i', 'o')

# adding tuple
vowels.add(tup)
print('Vowels are:', vowels)

# adding same tuple again
vowels.add(tup)
print('Vowels are:', vowels)

Output:


Vowels are: {('i', 'o'), 'e', 'u', 'a'}
Vowels are: {('i', 'o'), 'e', 'u', 'a'}

You can also add tuples to a set. And like normal elements, you can add the same tuple only once.

Thanks for reading !

Learn More

Python programming

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Guide to Python Programming Language

Guide to Python Programming Language

Python Hello World Program - Create & Run Your First Python Program in PyCharm

Python Hello World Program - Your first step towards Python world. Learn how to create the Hello World Python program in PyCharm.

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Learn Python Programming

Learn Python Programming

Python Programming & Data Handling

Python Programming & Data Handling