Created
June 15, 2017 21:45
-
-
Save vijayanandrp/5c85539fe96dc62ba7f5db8fd22f5254 to your computer and use it in GitHub Desktop.
Simple examples to understand Sets in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| Set - an unordered collection of unique and immutable objects | |
| """ | |
| def main(): | |
| x = set('abcdef') | |
| y = set('bdexyz') | |
| print "X = ", x | |
| print "Y = ", y, '\n' | |
| print "Difference = ", x - y | |
| print "Union = ", x | y | |
| print "Intersection = ", x & y | |
| print "Symmetric Difference (XOR) = ", x ^ y | |
| print "Superset = ", x > y | |
| print "subset = ", x < y, '\n' | |
| for item in set('abc'): | |
| print item * 3 | |
| print "'e' in x = ", 'e' in x, '\n' | |
| z = x.intersection(y) | |
| print z | |
| z.add('SPAM') # insert one item | |
| print z | |
| z.update(set(['X', 'Y'])) # inserts multiple items | |
| print z | |
| z.remove('b') | |
| print z, '\n' | |
| S = {i for i in range(1, 4)} | |
| print S | |
| print "Type = ", type(S) | |
| print "Union = ", S | set([3, 4]) | |
| print "Union = ", S.union([3, 4]) | |
| print "Intersection = ", S.intersection((1, 3, 5)) | |
| print "Subset = ", S.issubset(range(-5, 5)), '\n' | |
| print "Union = ", {1, 2, 3} | {4, 5} | |
| print "Union = ", {1, 2, 3}.union([3, 4]) | |
| print "Intersection = ", {1, 2, 3}.intersection((1, 3, 5)) | |
| print "Subset = ", {1, 2, 3}.issubset(range(-5, 5)), '\n' | |
| S = 'spammapaas' # Strings | |
| S = set(S) | |
| print S | |
| S.add('alot') | |
| print S | |
| S.add((1, 2, 3)) # No list or dict but tuple is ok | |
| print S, '\n' | |
| # Sets are used to remove the duplicates | |
| L = [1, 1, 2, 5, 4, 3, 7, 8, 2, 5, 9, 8, 0] | |
| print "L = ", L | |
| print "set(L) = ", set(L) | |
| L = list(set(L)) | |
| print "L = ", L, '\n' | |
| print set(dir(bytes)) - set(dir(bytearray)) | |
| print set(dir(bytearray)) - set(dir(bytes)) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment