sets in python
Set example
To create a set, we use the set() function.
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)
To remove all elements from sets:
To add elements to a set:
Remove elements to a set
To remove elements to a set:
To find the difference between two sets use:
Be aware that x.difference(y) is different from y.difference(x).
To create a set, we use the set() function.
#!/usr/bin/env python x = set(["Postcard", "Radio", "Telegram"]) print(x) |
#!/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 setTo 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) |
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) ) |
Subset
To test if a set is a subset use:
Super-set
To test if a set is a super-set:
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> |
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:
|
Comments
Post a Comment