Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Python Sets


Set

Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*, and unindexed.



Sets are written with curly brackets.

Example-
Create a Set:

thisset = {"apple", "banana", "cherry"} print(thisset)


Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.


Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by index or key.


Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.


Duplicates Not Allowed

Sets cannot have two items with the same value.

Example-
Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)


Get the Length of a Set

To determine how many items a set has, use the len() function.

Example-
Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))


Set Items - Data Types

Set items can be of any data type:

Example-
String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}


type()

From Python's perspective, sets are defined as objects with the data type 'set':

Example-
What is the data type of a set?

myset = {"apple", "banana", "cherry"}
print(type(myset))


Add Items

To add one item to a set use the add() method.

Example-
Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)


Update Set

To add items from another set into the current set, use the update() method.

Example-
Add elements from tropical into thisset:

thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)


Remove Item

To remove an item in a set, use the remove(), or the discard() method.

Example-
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)


Advertisement





it pathshaala : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java