3.2. Sequence Tuple

3.2.1. Rationale

  • Can store elements of any types

  • Immutable - cannot add, modify or remove items

3.2.2. Type Definition

  • () is used more often

  • tuple() is more readable

  • Single element tuple require comma at the end (important!)

  • Brackets are optional

  • Comma after last element of one element tuple is optional

data = ()
data = tuple()
Code 3.4. Single element tuple require comma at the end (important!)
data = (1,)
data = 1,
Code 3.5. Brackets are optional and comma after last element of one element tuple is optional
data = (1, 2, 3)
data = (1.1, 2.2, 3.3)
data = (True, False)
data = ('a', 'b', 'c')
data = ('a', 1, 2.2, True, None)

data = 1, 2, 3
data = 1.1, 2.2, 3.3
data = True, False
data = 'a', 'b', 'c'
data = 'a', 1, 2.2, True, None

3.2.3. Type Casting

  • tuple() converts argument to tuple

data = 'abcd'
tuple(data)
# ('a', 'b', 'c', 'd')
data = ['a', 'b', 'c', 'd']
tuple(data)
# ('a', 'b', 'c', 'd')
data = ('a', 'b', 'c', 'd')
tuple(data)
# ('a', 'b', 'c', 'd')
data = {1, 2, 3}
tuple(data)
# ('a', 'b', 'c', 'd')
data = frozenset({'a', 'b', 'c', 'd'})
tuple(data)
# ('a', 'b', 'c', 'd')

3.2.4. GetItem

data = ('a', 'b', 'c', 'd')

data[0]         # 'a'
data[1]         # 'b'
data[2]         # 'c'
data[3]         # 'd'

3.2.5. Tuple or Int, Float, Str

data = 1
type(data)
# <class 'int'>

data = 1,
type(data)
# <class 'tuple'>

data = 1.
type(data)
# <class 'float'>
type(1.2)        # <class 'float'>
type(1,2)        # <class 'tuple'>
type(1.2,)       # <class 'tuple'>
type(1,2.3)      # <class 'tuple'>

type(1.)         # <class 'float'>
type(1,)         # <class 'tuple'>
type(1.,)        # <class 'tuple'>
type(.2)         # <class 'float'>
type(.2,)        # <class 'tuple'>
type(1.2)        # <class 'float'>
type(1)          # <class 'int'>

type(1.,1.)      # <class 'tuple'>
type(.2,.2)      # <class 'tuple'>
type(1.,.2)      # <class 'tuple'>

type('foo')      # <class 'str'>
type('foo',)     # <class 'tuple'>
type('foo'.)     # SyntaxError: invalid syntax

3.2.6. Tuple or List

Both:

  • ordered

  • possible to getitem and slice

  • elements can be duplicated

  • elements of any types

Tuple:

  • immutable

  • one contingent block of data in memory

List:

  • mutable

  • implemented in memory as list of pointers to objects

  • objects are scattered in memory

from sys import getsizeof


a = [1, 2, 3]
b = (1, 2, 3)

getsizeof(a)
# 120

getsizeof(b)
# 64
../../_images/memory-tuple.png

Figure 3.1. Define tuple

../../_images/memory-list.png

Figure 3.2. Define list

../../_images/memory-all.png

Figure 3.3. Define str, tuple and list

3.2.7. Assignments

Code 3.6. Solution
"""
* Assignment: Sequence Tuple Create
* Filename: sequence_tuple_create.py
* Complexity: easy
* Lines of code to write: 1 lines
* Estimated time: 2 min

English:
    1. Create tuple `result` with elements:
        a. `'a'`
        b. `1`
        c. `2.2`
    2. Compare result with "Tests" section (see below)

Polish:
    1. Stwórz tuple `result` z elementami:
        a. `'a'`
        b. `1`
        c. `2.2`
    2. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Tests:
    >>> type(result)
    <class 'tuple'>
    >>> len(result)
    3
    >>> 'a' in result
    True
    >>> 1 in result
    True
    >>> 2.2 in result
    True
"""

Code 3.7. Solution
"""
* Assignment: Sequence Tuple Select
* Filename: sequence_tuple_select.py
* Complexity: easy
* Lines of code to write: 1 lines
* Estimated time: 5 min

English:
    1. Use data from "Given" section (see below)
    2. Create a `tuple` representing all species
    3. To convert table use multiline select with `alt` key in your IDE
    4. Do not use `slice`, `getitem`, `for`, `while` or any other control-flow statement
    5. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Stwórz `tuple` z nazwami gatunków
    3. Do konwersji tabelki wykorzystaj zaznaczanie wielu linijek za pomocą klawisza `alt` w Twoim IDE
    4. Nie używaj `slice`, `getitem`, `for`, `while` lub jakiejkolwiek innej instrukcji sterującej
    5. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Hints:
    * `ALT` + `left mouse button` = multiple select
    * `ALT` + `SHIFT` + `left mouse button drag` = vertical selection

Tests:
    >>> type(result)
    <class 'tuple'>
    >>> all(type(x) is str for x in result)
    True
    >>> ('sepal_length' not in result
    ...  and 'sepal_width' not in result
    ...  and 'petal_length' not in result
    ...  and 'petal_width' not in result
    ...  and 'species' not in result)
    True
    >>> len(result)
    5
    >>> result.count('virginica')
    2
    >>> result.count('setosa')
    1
    >>> result.count('versicolor')
    2
"""

# Given
DATA = ['sepal_length,sepal_width,petal_length,petal_width,species',
        '5.8,2.7,5.1,1.9,virginica',
        '5.1,3.5,1.4,0.2,setosa',
        '5.7,2.8,4.1,1.3,versicolor',
        '6.3,2.9,5.6,1.8,virginica',
        '6.4,3.2,4.5,1.5,versicolor']

Code 3.8. Solution
"""
* Assignment: Sequence Tuple Mean
* Filename: sequence_tuple_mean.py
* Complexity: medium
* Lines of code to write: 8 lines
* Estimated time: 8 min

English:
    1. Use data from "Given" section (see below)
    2. Calculate mean for each numerical values column
    3. To convert table use multiline select with `alt` key in your IDE
    7. Do not use `str.split()`, `slice`, `getitem`, `for`, `while` or any other control-flow statement
    5. Compare result with "Tests" section (see below)

Polish:
    1. Użyj danych z sekcji "Given" (patrz poniżej)
    2. Wylicz średnią arytmetyczną dla każdej z kolumn numerycznych
    3. Do konwersji tabelki wykorzystaj zaznaczanie wielu linijek za pomocą klawisza `alt` w Twoim IDE
    4. Nie używaj `str.split()`, `slice`, `getitem`, `for`, `while` lub jakiejkolwiek innej instrukcji sterującej
    5. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Hints:
    * `mean = sum(...) / len(...)`
    * `ALT` + `left mouse button` = multiple select
    * `ALT` + `SHIFT` + `left mouse button drag` = vertical selection
    * `ALT` + `SHIFT` + `right` = select word to the right (macOS)
    * `ALT` + `SHIFT` + `left` = select word to the left (macOS)
    * `CTRL` + `SHIFT` + `right` = select word to the right (Windows)
    * `CTRL` + `SHIFT` + `left` = select word to the left (Windows)
    * `CTRL` + `right` = jump over the word to the right
    * `CTRL` + `left` = jump over the word to the left
    * `CTRL` + `ALT` + L = Reformat Code on Windows
    * `CMD` + `ALT` + L = Reformat Code on macOS

Tests:
    >>> type(sepal_length)
    <class 'float'>
    >>> type(sepal_width)
    <class 'float'>
    >>> type(petal_length)
    <class 'float'>
    >>> type(petal_width)
    <class 'float'>
    >>> sepal_length
    5.859999999999999
    >>> sepal_width
    3.0200000000000005
    >>> petal_length
    4.14
    >>> petal_width
    1.34
"""

# Given
DATA = ['sepal_length,sepal_width,petal_length,petal_width,species',
        '5.8,2.7,5.1,1.9,virginica',
        '5.1,3.5,1.4,0.2,setosa',
        '5.7,2.8,4.1,1.3,versicolor',
        '6.3,2.9,5.6,1.8,virginica',
        '6.4,3.2,4.5,1.5,versicolor']