Python Set

Estimated reading: 2 minutes 640 views

Set Overview

Sets are used to store multiple items in a single variable.

A set is a collection which is unorderedunchangeable*, and unindexed.

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

Sets are written with curly brackets.

				
					tset = {1,2,3,4,5}
print(tset)
				
			

Access Items

You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keywor

				
					tset = {"Crircket","Caram","Football"}

for x in tset:
  print(x)
  
print("banana" in thisset) 
  
  
				
			

Add item to set

using add() , we can add the item to the list.

				
					tset = {"abc","def","ghi")
tset.add("ijk")
print(tset)
				
			

Removing item to set

using remove method we can delete the elemebts from set.

				
					tset = {"abc","def","ghi")
tset.remove("abc")
print(tset)
				
			

Set Loop items

Using For loop we can loop the items one by one.

				
					tset = {"abc","def","ghi")
for i in test:
  print(i)
				
			

Set union

it will combine the set and create a new set

				
					set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res1 = set1.union(set2)
print(res1)
				
			

Set intersection

it will get the common value from sets.

				
					set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res1 = set1.intersection(set2)
print(res1)
				
			

Set difference

Returns a set containing the difference between two or more sets
				
					set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res1 = set1.difference(set2)
print(res1)
				
			

Set symmetric_difference()

Returns a set with the symmetric differences of two sets

				
					set1 = {1,2,3,4,5}
set2 = {2,3,1,8,9}
res1 = set1.symmetric_difference(set2)
print(res1)
				
			

Set issubset()

Return True if all items in set a are present in set b:

				
					a = {1,2,3}
b = {4, 5, 4, 3, 2, 1}

res1 = a.issubset(b)

print(res1)
				
			

Set copy()

Returns a copy of the set

				
					a = {1,2,3}
res_final = a.copy()
print(res_final)
				
			

Leave a Comment

CONTENTS