3.5. Sequence Nested

3.5.1. List of Tuples

Listing 3.10. Get elements from list of tuple
data = [
    (4.7, 3.2, 1.3, 0.2, 'setosa'),
    (7.0, 3.2, 4.7, 1.4, 'versicolor'),
    (7.6, 3.0, 6.6, 2.1, 'virginica'),
]

data[2]
# (7.6, 3.0, 6.6, 2.1, 'virginica')

data[2][1]
# 3.0
Listing 3.11. Append elements using list.append()
data = [
    (4.7, 3.2, 1.3, 0.2, 'setosa'),
    (7.0, 3.2, 4.7, 1.4, 'versicolor'),
    (7.6, 3.0, 6.6, 2.1, 'virginica'),
]

row = (4.9, 2.5, 4.5, 1.7, 'virginica')
data.append(row)
# [(4.7, 3.2, 1.3, 0.2, 'setosa'),
#  (7.0, 3.2, 4.7, 1.4, 'versicolor'),
#  (7.6, 3.0, 6.6, 2.1, 'virginica'),
#  (4.9, 2.5, 4.5, 1.7, 'virginica')]
Listing 3.12. Append elements using list.extend()
data = [
    (4.7, 3.2, 1.3, 0.2, 'setosa'),
    (7.0, 3.2, 4.7, 1.4, 'versicolor'),
    (7.6, 3.0, 6.6, 2.1, 'virginica'),
]

row = (4.9, 2.5, 4.5, 1.7, 'virginica')
data.extend(row)
# [(4.7, 3.2, 1.3, 0.2, 'setosa'),
#  (7.0, 3.2, 4.7, 1.4, 'versicolor'),
#  (7.6, 3.0, 6.6, 2.1, 'virginica'),
#  4.9,
#  2.5,
#  4.5,
#  1.7,
#  'virginica']
Listing 3.13. list of tuple length
data = [
    (4.7, 3.2, 1.3, 0.2, 'setosa'),
    (7.0, 3.2, 4.7, 1.4, 'versicolor'),
    (7.6, 3.0, 6.6, 2.1, 'virginica'),
]

len(data)
# 3

len(data[2])
# 5

3.5.2. List of Lists

  • Multidimensional lists

Listing 3.14. Lists a, b, c, d contains the same values, but readability differs depending on whitespaces.
a = [[1,2,3],[4,5,6],[7,8,9]]

b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

c = [[1,2,3], [4,5,6], [7,8,9]]

d = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
Listing 3.15. Get elements from list of list
data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

data[0][0]
# 1

data[0][2]
# 3

data[2][1]
# 8
Listing 3.16. list of list length
data = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

len(data)
# 3

len(data[2])
# 3

3.5.3. Many Types

Listing 3.17. Get elements from union
data = [
    [1, 2, 3],
    (4, 5, 6),
    {7, 8, 9},
]

data[1]
# (4, 5, 6)

data[1][2]
# 6

data[2]
# {7, 8, 9}

data[2][1]
# TypeError: 'set' object is not subscriptable
Listing 3.18. Union length
data = [
    [1, 2],
    (3, 4, 5, 6),
    {7, 8, 9, 10, 11},
]

len(data)
# 3

len(data[0])
# 2

len(data[1])
# 4

len(data[2])
# 5

3.5.4. Assignments

3.5.4.1. Sequence Nesting Create

English
  1. Create nested sequence result with elements:

    • tuple: 1, 2, 3

    • list: 1.1, 2.2, 3.3

    • set: 'Mark Watney', 'Melissa Lewis', 'Jan Twardowski'

  2. Print result

  3. Print number of elements in result

Polish
  1. Stwórz zagnieżdżoną sekwencję result z elementami:

    • krotka: 1, 2, 3

    • lista: 1.1, 2.2, 3.3

    • zbiór: 'Mark Watney', 'Melissa Lewis', 'Jan Twardowski'

  2. Wypisz result

  3. Wypisz liczbę elementów result