Advertisement
Guest User

Untitled

a guest
Aug 28th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. ### TUPLES ###
  2.  
  3. * like lists, but they don't change size
  4. * properties: ordered, iterable, immutable, can contain multiple data types
  5.  
  6. ## create a tuple
  7. ```python
  8. digits = (0, 1, 'two') # create a tuple directly
  9. digits = tuple([0, 1, 'two']) # create a tuple from a list
  10. zero = (0,) # trailing comma is required to indicate it's a tuple
  11. ```
  12.  
  13. ## examine a tuple
  14. ```python
  15. digits[2] # returns 'two'
  16. len(digits) # returns 3
  17. digits.count(0) # counts the number of instances of that value (1)
  18. digits.index(1) # returns the index of the first instance of that value (1)
  19. ```
  20.  
  21. ## elements of a tuple cannot be modified
  22. ```python
  23. digits[2] = 2 # throws an error
  24. ```
  25.  
  26. ## concatenate tuples
  27. ```python
  28. digits = digits + (3, 4)
  29. ```
  30.  
  31. ## create a single tuple with elements repeated (also works with lists)
  32. ```python
  33. (3, 4) * 2 # returns (3, 4, 3, 4)
  34. ```
  35.  
  36. ## sort a list of tuples
  37. ```python
  38. tens = [(20, 60), (10, 40), (20, 30)]
  39. sorted(tens) # sorts by first element in tuple, then second element
  40. # returns [(10, 40), (20, 30), (20, 60)]
  41. ```
  42.  
  43. ## tuple unpacking
  44. ```python
  45. bart = ('male', 10, 'simpson') # create a tuple
  46. (sex, age, surname) = bart # assign three values at once
  47. ```python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement