{:check ["true"],
 :rank ["list" "list_memory_model" "tuple" "set" "dict"]}

Index

Aggregate Types in Python

  • List
  • Memory model of lists
  • Tuple
  • Dictionary
  • Set

List

Lists

Python list is arguably the most versatile compound data types.

Construction

One can construct lists with the list syntax: [ ... ]. Elements are separated by ,.

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

>>> len(squares)
5

Indexing by position

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25

Indexing by range

# indexing from start to end
# start - inclusive
# end - exclusive
>>> squares[0:3]
[1, 4, 9]
>>> squares[1:3]
[4, 9]

# start can be omitted, the
# default start is 0.
>>> squares[:3]
[1, 4, 9]
>>> squares[:5]
[1, 4, 9, 16, 25]

# the end can be omitted, and
# the default end is the
# length of the list.
>>> squares[3:]
[16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]

List Memory Model

List memory model

Consider the following code operating on Python lists:

x = [1]
y = [2]
z = [3]

list1 = [x, y, z]
>>> print(list1)

[[1], [2], [3]]

Memory layout

    +-----+-----+-----+
    |  *  |  *  |  *  |  
    +--|--+--|--+--|--+
       |     |     |
       |     |     |
   x   | y   | z   |
    \  |  \  |  \  |  
     \ |   \ |   \ |  
     +---+ +---+ +---+
     | 1 | | 2 | | 3 |
     +---+ +---+ +---+

Side-effects

  • Modifying x will also affect the content of list

    >>> x[0] = -1
    >>> print(list1)
    
    [[-1], [2], [3]]
    
  • Modifying list will also affect the

Tuple

Tuples

Tuples are immutable lists.

  1. No element can be removed from a tuple.
  2. No element can be added to a tuple.
  3. Entries of a tuple cannot be altered.

Construction and indexing

  • Construction (__, __, __). The parenthese are optional.

    >>> t = (12345, 54321, 'hello!')
    >>> t = 12345, 54321, 'hello!'
    
  • Indexing is the same as lists

    >>> t[0]
    12345
    
  • Tuples can be nested.

    >>> t
    (12345, 54321, 'hello!')
    >>> # Tuples may be nested:
    ... u = t, (1, 2, 3, 4, 5)
    >>> u
    ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
    
  • Tuples are immutable. We cannot change the tuple value.

    >>> # Tuples are immutable:
    ... t[0] = 88888
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
    
  • However, if the elements are mutable data structures, we can update the element values themselves.

    >>> # but they can contain mutable objects:
    ... v = ([1, 2, 3], [3, 2, 1])
    >>> v
    ([1, 2, 3], [3, 2, 1])
    >>> v[0].append(4)
    >>> v
    ([1, 2, 3, 4], [3, 2, 1])
    
  • Tuples can be empty. The parentheses are necessary.

    empty = ()
    
  • Singletons are tuples with just one element. The syntax requires the trailing comma ,. The parentheses are optional.

    one_thing = ('hello',)
    one_thing = 'hello',
    
  • We can unpack the tuples into variables.

    >>> t
    (12345, 54321, 'hello')
    >>> x,y,z = t
    >>> x
    12345
    >>> y
    54321
    >>> z
    "hello"
    

Set

Sets

A set is a collection with no ordering and does not allow duplicate elements.

Construction and access

  • The construction of set is done with the curly braces.

    >>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
    >>> print(basket)                      # show that duplicates have been removed
    {'orange', 'banana', 'pear', 'apple'}
    
  • We can check if a element belongs to a set with the in operator.

    >>> 'orange' in basket                 # fast membership testing
    True
    >>> 'crabgrass' in basket
    False
    
  • The set(...) function converts a sequence into a set by removing any duplicates.

    >>> # Demonstrate set operations on unique letters from two words
    ...
    >>> a = set('abracadabra')
    >>> b = set('alacazam')
    >>> a                                  # unique letters in a
    {'a', 'r', 'b', 'c', 'd'}
    
  • Set arithmetics are:

    1. set difference
    2. set union
    3. set intersection
    4. set exclusive-union (xor)
    >>> a - b                              # letters in a but not in b
    {'r', 'd', 'b'}
    >>> a | b                              # letters in a or b or both
    {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
    >>> a & b                              # letters in both a and b
    {'a', 'c'}
    >>> a ^ b                              # letters in a or b but not both
    {'r', 'd', 'b', 'm', 'z', 'l'}
    

Dict

Dictionaries

Dictionary is one of the most important data type in Python. Unlike lists, the elements are indexed by arbitrary (immutable) values.

Definition

  • Indexing values are the keys in the dictionary.
  • The indexed elements are the values in the dictionary.

All keys must be unique, but not the values.

Construction

  • Construction using { key:val, ...}

    >>> tel = {'jack': 4098, 'sape': 4139}
    
  • Construction using the dict(...) constructor:

    >>> tel = dict(jack=4098, sape=4139)
    
  • Construction using dict(...) to construct the dictionary from a sequence of key/value pairs.

    >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    {'sape': 4139, 'guido': 4127, 'jack': 4098}
    

Access

  • We can retrieve the value of a given key.

    >>> tel['jack']
    4098
    
  • We can create new key/value pairs in the dictionary.

    >>> tel['guido'] = 4127
    >>> tel
    {'jack': 4098, 'sape': 4139, 'guido': 4127}
    
  • We can delete a key and its value.

    >>> del tel['sape']
    >>> tel['irv'] = 4127
    >>> tel
    {'jack': 4098, 'guido': 4127, 'irv': 4127}
    
  • If we interprete a dictionary as a list, we get the list of keys.

    >>> list(tel)
    ['jack', 'guido', 'irv']
    >>> sorted(tel)
    ['guido', 'irv', 'jack']
    
  • We can also check if a key exists in a dictionary using the in operator.

    >>> 'guido' in tel
    True
    >>> 'jack' not in tel
    False
    
  • We can get a sequence of key/value pairs (as tuples) using the .items() method.

    for (name, number) in tel.items():
        print("%s: %s" % (name, number))