Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### TUPLES ###
- * like lists, but they don't change size
- * properties: ordered, iterable, immutable, can contain multiple data types
- ## create a tuple
- ```python
- digits = (0, 1, 'two') # create a tuple directly
- digits = tuple([0, 1, 'two']) # create a tuple from a list
- zero = (0,) # trailing comma is required to indicate it's a tuple
- ```
- ## examine a tuple
- ```python
- digits[2] # returns 'two'
- len(digits) # returns 3
- digits.count(0) # counts the number of instances of that value (1)
- digits.index(1) # returns the index of the first instance of that value (1)
- ```
- ## elements of a tuple cannot be modified
- ```python
- digits[2] = 2 # throws an error
- ```
- ## concatenate tuples
- ```python
- digits = digits + (3, 4)
- ```
- ## create a single tuple with elements repeated (also works with lists)
- ```python
- (3, 4) * 2 # returns (3, 4, 3, 4)
- ```
- ## sort a list of tuples
- ```python
- tens = [(20, 60), (10, 40), (20, 30)]
- sorted(tens) # sorts by first element in tuple, then second element
- # returns [(10, 40), (20, 30), (20, 60)]
- ```
- ## tuple unpacking
- ```python
- bart = ('male', 10, 'simpson') # create a tuple
- (sex, age, surname) = bart # assign three values at once
- ```python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement