4. Simple Collections

4.1. list

  • Can store elements of any types
  • Mutable - can add, remove, and modify items
  • Brackets are required
  • Comma after last element is optional

4.1.1. Defining list

  • list() is more readable
  • [] is used more often
my_list = []
my_list = list()
my_list = [1]
my_list = [1,]
my_list = [1, 2.0, None, False, 'José']

4.1.2. Nested list

my_list = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
my_list = [1, 2.0, [1, 'hello'], None, [2, 1]]

4.1.3. Slicing list

  • Slicing works the same as for str
my_list = [1, 2.0, None, False, 'José']

my_list[1]             # 2.0
my_list[2:4]           # [None, False]
my_list[::2]           # [1, None, 'José']
my_list[-1]            # 'José'

4.1.4. Adding elements

my_list = [1, 2]

my_list + [3, 4]        # [1, 2, 3, 4]

4.1.5. Appending elements

my_list = [1, 2]

my_list.append(3)       # [1, 2, 3]
my_list.append([4, 5])  # [1, 2, 3, [4, 5]]

4.1.6. Extending lists

my_list = [1, 2]

my_list.extend([3, 4])  # [1, 2, 3, 4]

4.1.7. Inserting elements at specific position

my_list = [1, 2]

my_list.insert(0, 'a')  # ['a', 1, 2]

4.1.8. Length of a list

my_list = [1, 2, 3]

len(my_list)    # 3

4.2. set

  • Can store elements of any hashable types
  • Only unique values
  • Mutable - can add, remove, and modify items
  • Brackets are required
  • Comma after last element is optional

4.2.1. Defining set

  • Defining only with set()
my_set = set()
my_set = {1}
my_set = {1,}
my_set = {1, 3, 1}          # {1, 3}
my_set = {1, 2.0, 'Jose'}   # {1, 2.0, 'Jose'}
my_set = {1, 2.0, [3, 4]}   # TypeError: unhashable type: 'list'
my_set = {1, 2.0, {3, 4}}   # TypeError: unhashable type: 'set'

4.2.2. Adding items

my_set = {1, 2, 3}          # {1, 2, 3}

my_set.add(4)               # {1, 2, 3, 4}
my_set.add(4)               # {1, 2, 3, 4}
my_set.add(3)               # {1, 2, 3, 4}

4.2.3. Adding many items

my_set = {1, 2, 3}          # {1, 2, 3}

my_set.update([4, 5])       # {1, 2, 3, 4, 5}
my_set = {1, 2, 3}          # {1, 2, 3}

my_set.update({4, 5})       # {1, 2, 3, 4, 5}

4.2.4. Mathematical set operations

{1,2} - {2,3}    # {1}        # Subtract
{1,2} | {2,3}    # {1, 2, 3}  # Sum
{1,2} & {2,3}    # {2}        # Union
{1,2} ^ {2,3}    # {1, 3}     # Symmetrical difference
{1,2} + {3,4}    # TypeError: unsupported operand type(s) for +: 'set' and 'set'

4.2.5. Slicing set

  • Slicing set is not possible
my_set = {1, 2.0, None, False, 'José'}

my_set[1]                   # TypeError: 'set' object does not support indexing
my_set[2:4]                 # TypeError: 'set' object does not support indexing

4.2.6. Length of a set

my_set = {1, 2, 3}

len(my_set)                 # 3

4.2.7. Converting list to set deduplicate items

names = ['Matt', 'Иван', 'José', 'Matt']

unique_names = set(names)
# {'Matt', 'Иван', 'José'}

4.3. tuple

  • Can store elements of any types
  • Immutable - cannot add, modify or remove items
  • Brackets are optional
  • Comma after last element is optional
  • Single element tuple require comma at the end (important!)

4.3.1. Defining tuple

  • tuple() is more readable
  • () is used more often
my_tuple = ()
my_tuple = tuple()
my_tuple = 1,
my_tuple = (1,)
my_tuple = 1, 2
my_tuple = (1, 2)
my_tuple = 1, 2.0, None, False, 'José'
my_tuple = (1, 2.0, None, False, 'José')

4.3.2. Slicing tuple

my_tuple = (1, 2, 3, 4, 5)

my_tuple[2]             # 3
my_tuple[-1]            # 5
my_tuple[:3]            # (1, 2, 3)
my_tuple[3:]            # (4, 5)
my_tuple[::2]           # (1, 3, 5)
my_tuple[1:4]           # (2, 3, 4)

4.3.3. Length of a tuple

my_tuple = (1, 2, 3)

len(my_tuple)           # 3

4.4. Unpacking sequences to variables

a, b, c = 1, 2, 3
a, b, c = (1, 2, 3)
a, b, c = [1, 2, 3]
a, b, c = {1, 2, 3}

4.5. How Python understands types?

what = 1.2        # float
what = 1,2        # tuple

what = (1.2)      # float
what = (1,2)      # tuple
what = 1.2,       # tuple with float
what = 1,2.3      # tuple with int and float

what = (1.2,)     # tuple with float
what = (1,2.3)    # tuple with int and float
what = 'foo'      # str
what = 'foo',     # tuple with str
what = 'foo'.     # SyntaxError: invalid syntax

what = ('foo')    # str
what = ('foo',)   # tuple with str
what = ('foo'.)   # SyntaxError: invalid syntax
what = 1.        # float
what = .5        # float
what = 1.0       # float
what = 1         # int

what = (1.)      # float
what = (.5)      # float
what = (1.0)     # float
what = (1)       # int
what = 10.5      # float
what = 10,5      # tuple with two ints
what = 10.       # float
what = 10,       # tuple with int
what = 10        # int

what = (10.5)    # float
what = (10,5)    # tuple with two ints
what = (10.)     # float
what = (10,)     # tuple with int
what = (10)      # int
what = 1.,1.     # tuple with two floats
what = .5,.5     # tuple with two floats
what = 1.,.5     # tuple with two floats

what = (1.,1.)   # tuple with two floats
what = (.5,.5)   # tuple with two floats
what = (1.,.5)   # tuple with two floats

4.6. Built-in functions on sequences

4.6.1. len()

numbers = [1, 2, 3, 4, 5]

len(numbers)                   # 5
len('Max')                     # 3
len({'id': 3, 'name': 'Max'})  # 2

4.6.2. min()

numbers = [1, 2, 3, 4, 5]

min(numbers)  # 1
min(3, 1, 5)  # 1

4.6.3. max()

numbers = [1, 2, 3, 4, 5]

max(numbers)  # 5
max(3, 1, 5)  # 5

4.6.4. sorted()

   numbers = [3, 1, 2]

   numbers = sorted(numbers)
   print(numbers)  # [1, 2, 3]


``list.sort()``

numbers = [3, 1, 2]

numbers.sort() print(numbers)

  • sorted() zwraca posortowaną listę, ale nie zapisuje zmienionej kolejności
  • .sort() zmienia listę na stałe
numbers = [3, 1, 2]

sorted(numbers) # returns [1, 2, 3]
print(numbers)  # [3, 1, 2]
numbers = [3, 1, 2]

numbers.sort()  # returns None
print(numbers)  # [1, 2, 3]

4.7. Membership Operators

Tab. 4.2. Membership operators
Operand Description  
x == y x == 18 value of x is equal to y
x != y x != 18 value of x is not equal to y
x in y x in [1, 2, 3] x contains y
x not in y x not in [1, 2, 3] x not contains y

4.8. More advanced topics

Note

The topic will be continued in Intermediate and Advanced part of the book

4.9. Assignments

4.9.1. Simple collections

  1. Stwórz a: tuple z cyframi 0, 1, 2, 3
  2. Stwórz b: list z cyframi 2, 3, 4, 5
  3. Stwórz c: set, który będzie zawierał co drugie elementy z a i b
  4. Wyświetl c na ekranie
About:
  • Filename: sequences_simple.py
  • Lines of code to write: 5 lines
  • Estimated time of completion: 10 min
The whys and wherefores:
 
  • Definiowanie i korzystanie z list, tuple, set
  • Slice zbiorów danych
  • Rzutowanie i konwersja typów

4.9.2. Iris dataset

  1. Mając dane z listingu poniżej

    DATA = (
        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',
        4.7, 3.2, 1.3, 0.2, 'setosa',
    )
    

# Za pomocą slice wyodrębnij zmienną…

  1. features: List[Tuple[float]] z wynikami pomiarów

    features = [
        (5.8, 2.7, 5.1, 1.9),
        (5.1, 3.5, 1.4, 0.2),
        (5.7, 2.8, 4.1, 1.3),
        (6.3, 2.9, 5.6, 1.8),
        (6.4, 3.2, 4.5, 1.5),
        (4.7, 3.2, 1.3, 0.2),
    ]
    
  2. labels: List[str], która będzie zawierała w kolejności wszystkie nazwy gatunków

    labels = [
        'virginica',
        'setosa',
        'versicolor',
        'virginica',
        'versicolor',
        'setosa',
    ]
    
  3. species: Set[str], która jest unikalnym zbiorem gatunków (na podstawie labels)

    species = {
        'versicolor',
        'setosa',
        'virginica',
    }
    
About:
  • Filename: sequences_iris.py
  • Lines of code to write: 30 lines
  • Estimated time of completion: 20 min
The whys and wherefores:
 
  • Definiowanie i korzystanie z list, tuple, set
  • Slice zbiorów danych
  • Rzutowanie i konwersja typów