Table of Contents
In this tutorial, we will discuss the concept of Set datatype in Python programming language.
Set is a data type in Python which is an unordered collection of unique elements. Set has no duplicates and we can add or remove from the set.
How to make a set in python?
Set is a Datatype in Python. When creating a set, we can place element inside the curly braces {}, and elements separated by a comma, or we can use the pre-defined function set().
Set can have different data types (float, integer, string, tuple) and any number of items.
Example of set
set([24, 36, 12, 48])
Set can not have duplicate elements
set([32, 1, 43, 21, 54, 56])
Only display single elements
set([8, 2, 4, 6])
set([8, 1, 2, 4, 6])
set([8, 2, 4, 6])
set([1, 2, 3, 4, 5, 6, 7, 8])
How to remove or discard element from set
use remove() function
A particular item can be removed from the set using remove() method
use discard() function
A particular item can be removed from the set using discard() method
When the above code is executed, it produces the following results
set([15, 41, 11, 21, 13])
set([15, 41, 11, 21])
How to clear the element from the set
All item can be cleared from the set using clear() method
when the above code is executed, it produces the following results
How to pop element from the set
We can remove an item using the pop() method
When the above code is executed, it produces the following results
set([‘e’, ‘d’, ‘H’, ‘l’, ‘o’, ‘r’, ‘w’])
e
d
Set union of X and Y is a set of all elements from both sets.
The union is performed using | operator and same can be fulfilled by the union() pre-defined method in python.
Related post
Data type in Python List in Python
Tuple in Python Dictionary in Python
Subtract two numbers using method overriding Program 1
PHP Star triangle Pattern program Here's a simple Java program that demonstrates how to print…
Using Function or Method to Write to temperature conversion: Fahrenheit into Celsius In this article,…
Function or method of temperature conversion from Fahrenheit into Celsius In this article, we will…
Write temperature conversion program: from Fahrenheit to Celsius In this article, we will discuss the…
How to write a program to convert Fahrenheit into Celsius In this article, we will…
This website uses cookies.