Skip to content

Instantly share code, notes, and snippets.

@fabsta
Created August 28, 2016 20:25
Show Gist options
  • Save fabsta/66749b841978bd9008357e10a0ebb563 to your computer and use it in GitHub Desktop.
Save fabsta/66749b841978bd9008357e10a0ebb563 to your computer and use it in GitHub Desktop.

TUPLES

  • like lists, but they don't change size
  • properties: ordered, iterable, immutable, can contain multiple data types

create a tuple

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

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

digits[2] = 2       # throws an error

concatenate tuples

digits = digits + (3, 4)

create a single tuple with elements repeated (also works with lists)

(3, 4) * 2          # returns (3, 4, 3, 4)

sort a list of tuples

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

bart = ('male', 10, 'simpson')  # create a tuple
(sex, age, surname) = bart      # assign three values at once
```python
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment