Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # SETS
- * like dictionaries, but with keys only (no values)
- * properties: unordered, iterable, mutable, can contain multiple data types
- * made up of unique elements (strings, numbers, or tuples)
- ## create an empty set
- ```python
- empty_set = set()
- ```
- ## create a set
- ```python
- languages = {'python', 'r', 'java'} # create a set directly
- snakes = set(['cobra', 'viper', 'python']) # create a set from a list
- ```
- ## examine a set
- ```python
- len(languages) # returns 3
- 'python' in languages # returns True
- ```
- ## set operations
- ```python
- languages & snakes # returns intersection: {'python'}
- languages | snakes # returns union: {'cobra', 'r', 'java', 'viper', 'python'}
- languages - snakes # returns set difference: {'r', 'java'}
- snakes - languages # returns set difference: {'cobra', 'viper'}
- ```
- ## modify a set (does not return the set)
- ```python
- languages.add('sql') # add a new element
- languages.add('r') # try to add an existing element (ignored, no error)
- languages.remove('java') # remove an element
- languages.remove('c') # try to remove a non-existing element (throws an error)
- languages.discard('c') # removes an element if present, but ignored otherwise
- languages.pop() # removes and returns an arbitrary element
- languages.clear() # removes all elements
- languages.update('go', 'spark') # add multiple elements (can also pass a list or set)
- ```
- ## get a sorted list of unique elements from a list
- ```python
- sorted(set([9, 0, 2, 1, 0])) # returns [0, 1, 2, 9]
- ```
- ## set comprehension
- ```python
- fruits = ['apple', 'banana', 'cherry']
- unique_lengths = {len(fruit) for fruit in fruits} # {5, 6}
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement