Python sets data type | Set Data type in python

 


Set Data Type

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. Set items are unordered, unchangeable, and do not allow duplicate values. 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. Set items are unchangeable, meaning that we cannot change the items after the set has been created. Sets cannot have two items with the same (duplicate) value.

Once a set is created, you cannot change its items, but you can remove items and add new items.

Note: Set items are unchangeable, but you can remove items and add new items.

Example

Create a Set:

st = {"apple""banana""orange"}
print(st)

# Note: the set list is unordered, meaning: the items will appear in a random order.

# Refresh this page to see the change in the result.

Output:

{'banana', 'apple', ‘orange’}

Example

Duplicate values will be ignored:

st = {"apple""banana""orange", "apple"}
print(st)

Output:

{'banana', 'apple', ‘orange’}

Example

Get the number of items in a set:

st = {"apple""banana""orange"}
print(st)

Output:

3

Set items can be of any data type:

Example

String, int and boolean data types:

set1 = {"apple""banana""cherry"}
set2 = {
15793}
set3 = {
TrueFalseFalse}

print(set1)

print(set2)

print(set3)

Output:

{'cherry', 'apple', 'banana'}

{1, 3, 5, 7, 9}

{False, True}

A set can contain different data types:

Example

A set with strings, integers and boolean values:

set1 = {"abc"34True40"male"}

print(set1)

Output:

{True, 34, 40, 'male', 'abc'}

type()

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

<class 'set'>

Example

What is the data type of a set?

st = {"apple""banana""cherry"}
print(type(st))

Output:

<class 'set'>

The set() Constructor

It is also possible to use the set() constructor to make a set.

Example

Using the set() constructor to make a set:

st = set(("apple""banana""cherry")) # note the double round-brackets
print
(st)

{'cherry', 'apple', 'banana'}

<<Previous                                                  Next>>

कोई टिप्पणी नहीं

टिप्पणी: केवल इस ब्लॉग का सदस्य टिप्पणी भेज सकता है.

Microsoft Word top 180 keyboard shortcuts

Microsoft Word top 180 keyboard shortcuts Download shortcut keys File: MS Word File - Click here MS Excel File - Click here PDF File - Click...

Blogger द्वारा संचालित.