python logo

python create set


Python hosting: Host, run, and code Python in the cloud!

Sets in Python


A set in Python is a collection of objects. Sets are available in Python 2.4 and newer versions. They are different from lists or tuples in that they are modeled after sets in mathematics.

Related course
Python Programming Bootcamp: Go from zero to hero

Set example
To create a set, we use the set() function.

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

If we add the same item element multiple times, they are removed. A set may not contain the same element multiple times.

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram", "Postcard"])
print(x)

Simple notation


If you use Python version 2.6 or a later version, you can use a simplified notation:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

y = {"Postcard","Radio","Telegram"}
print(y)

Set Methods


Clear elements from set
To remove all elements from sets:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.clear()
print(x)

Add elements to a set
To add elements to a set:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.add("Telephone")
print(x)

Remove elements to a set
To remove elements to a set:

!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.remove("Radio")
print(x)

Difference between two sets
To find the difference between two sets use:

#!/usr/bin/env python
x = set(["Postcard", "Radio", "Telegram"])
y = set(["Radio","Television"])
print( x.difference(y) )
print( y.difference(x) )

Be aware that x.difference(y) is different from y.difference(x).

Subset
To test if a set is a subset use:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issubset(y) )<b>
</b>

Super-set
To test if a set is a super-set:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issuperset(y) )

Intersection
To test for intersection, use:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.intersection(y) )

Related course
Python Programming Bootcamp: Go from zero to hero

BackNext





Leave a Reply: