| 34 | Examples using Python's built-in set: |
| 35 | |
| 36 | {{{ |
| 37 | # Union |
| 38 | >>> list1=range(5) # [0,1,2,3,4] |
| 39 | >>> list2=range(3,7) # [3,4,5,6] |
| 40 | >>> union = set(list1).union(list2) |
| 41 | >>> print union |
| 42 | set([0, 1, 2, 3, 4, 5, 6]) |
| 43 | >>> print list(union) |
| 44 | [0, 1, 2, 3, 4, 5, 6] |
| 45 | |
| 46 | # Intersection |
| 47 | >>> intersection = set(list1).intersection(list2) |
| 48 | >>> print intersection |
| 49 | set([3, 4]) |
| 50 | >>> print list(intersection) |
| 51 | [3, 4] |
| 52 | |
| 53 | # Difference |
| 54 | >>> difference = set(list1) - set(list2) |
| 55 | >>> print difference |
| 56 | set([0, 1, 2]) |
| 57 | |
| 58 | # Symmetric difference |
| 59 | # Return a new set with elements in either the set or other but not both. |
| 60 | >>> symmetric_difference = set(list1).symmetric_difference(list2) |
| 61 | >>> print symmetric_difference |
| 62 | set([0, 1, 2, 5, 6]) |
| 63 | >>> |
| 64 | |
| 65 | |
| 66 | }}} |