Advertisement
Guest User

Untitled

a guest
Aug 28th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. # SETS
  2.  
  3. * like dictionaries, but with keys only (no values)
  4. * properties: unordered, iterable, mutable, can contain multiple data types
  5. * made up of unique elements (strings, numbers, or tuples)
  6.  
  7. ## create an empty set
  8. ```python
  9. empty_set = set()
  10. ```
  11.  
  12. ## create a set
  13. ```python
  14. languages = {'python', 'r', 'java'} # create a set directly
  15. snakes = set(['cobra', 'viper', 'python']) # create a set from a list
  16. ```
  17.  
  18. ## examine a set
  19. ```python
  20. len(languages) # returns 3
  21. 'python' in languages # returns True
  22. ```
  23.  
  24. ## set operations
  25. ```python
  26. languages & snakes # returns intersection: {'python'}
  27. languages | snakes # returns union: {'cobra', 'r', 'java', 'viper', 'python'}
  28. languages - snakes # returns set difference: {'r', 'java'}
  29. snakes - languages # returns set difference: {'cobra', 'viper'}
  30. ```
  31.  
  32. ## modify a set (does not return the set)
  33. ```python
  34. languages.add('sql') # add a new element
  35. languages.add('r') # try to add an existing element (ignored, no error)
  36. languages.remove('java') # remove an element
  37. languages.remove('c') # try to remove a non-existing element (throws an error)
  38. languages.discard('c') # removes an element if present, but ignored otherwise
  39. languages.pop() # removes and returns an arbitrary element
  40. languages.clear() # removes all elements
  41. languages.update('go', 'spark') # add multiple elements (can also pass a list or set)
  42. ```
  43.  
  44. ## get a sorted list of unique elements from a list
  45. ```python
  46. sorted(set([9, 0, 2, 1, 0])) # returns [0, 1, 2, 9]
  47. ```
  48.  
  49.  
  50. ## set comprehension
  51. ```python
  52. fruits = ['apple', 'banana', 'cherry']
  53. unique_lengths = {len(fruit) for fruit in fruits} # {5, 6}
  54. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement