Python sets data type

  • Python Set is a collection that is unordered, unindexed, No duplicate members.
  • Python sets are written with curly brackets { }.

Note: Sets are items will appear in random order because set is unordered.

Example

Create a set

y={1,2,3,4,5,6,7} #This is a set

print(x)
Output
[1, 2, 3, 4, 5, 6, 7]

How to Access Set Items

  • The sets have unordered the items have no index but using a loop we access the set items.
Example

Create a list and access using for loop

t={"amit", "sumit", "ravi"}
for i in t:
 print(i)
Output
amit
sumit
ravi

Check if control statement in sets

  • Using in keywords to determine if a specified item is present in sets.
Example

Create a set and use if control statements

t={"amit", "sumit", "ravi"}
if "sumit" in t:
 print("Yes, 'sumit' is found in set")
else:
 print("No, 'sumit' is found in set")
Output
Yes, ‘sumit’ is found in set

How to Change Item Value in set

  • Once a set is created, you cannot change its items, but you can add new items.
add( ) and update( ) method
  •  The add( ) method is used to add one item to a set.
  •  The update( ) method is used to add more than one item to a set.
Example

Use of add( ) method

t={"amit", "sumit", "ravi"}
t.add("Mohan")
print(t)
Output
{‘Mohan’, ‘ravi’, ‘sumit’, ‘amit’}
Example

Use of update( ) method

t={"amit", "sumit", "ravi"}
t.update(["Mohan","Kiran","Komal"])
print(t)
Output
{‘Kiran’, ‘ravi’, ‘amit’, ‘Mohan’, ‘Komal’, ‘sumit’}