Dec 12, 2019 in Python
Q: Python Set

1 Answer

0 votes
Dec 12, 2019
The set in python can be defined as the unordered collection of various items enclosed within the curly braces. The elements of the set can not be duplicate. The elements of the python set must be immutable.

Unlike other collections in python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together or we can get the list of elements by looping through the set.

Creating a set

The set can be created by enclosing the comma separated items with the curly braces. Python also provides the set method which can be used to create the set by the passed sequence.

Example 1: using curly braces

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}  

print(Days)  

print(type(Days))  

print("looping through the set elements ... ")  

for i in Days:  

    print(i)  

Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}

<class 'set'>

looping through the set elements ...

Friday

Tuesday

Monday

Saturday

Thursday

Sunday

Wednesday

Example 2: using set() method

Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])  

print(Days)  

print(type(Days))  

print("looping through the set elements ... ")  

for i in Days:  

    print(i)  

Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}

<class 'set'>

looping through the set elements ...

Friday

Wednesday

Thursday

Saturday

Monday

Tuesday

Sunday
Click here to read more about Python
Click here to read more about Insurance

Related questions

0 votes
Dec 14, 2019 in Python
0 votes
Jun 24, 2020 in Python
...