8. Structured Data

8.1 Data structures

  1. List x = [1, 2, 3]

    • mutable: add, delete, or change values

  2. Tuple x = (1, 2, 3)

    • immutable

  3. Dictionary x = {'a': 1, 'b': 2, 'c': 3}

    • key-value pairs, (hash array in other languages)

    • also mutable.

  4. Set x = {1, 2, 3}

    • sets are mutable, but set elements must be immutable

8.2 Lists

  • example: game = ['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock']

  • game[1:3] returns two elements. First element is inclusive, second is non-inclusive.

  • game[begin:end:step] also works

  • To search a list, use the index method:

    • `i = game.index(‘Paper’)

  • Lists are mutable, so you can append an item as

    • game.append('Computer')

  • Or you can insert at an index as:

    • game.insert(0, 'Computer')

    • This doesn’t overwrite the previous value, but inserts it.

  • To remove an item by value

    • game.remove('Paper')

  • Or remove an item from the end of the list:

    • game.pop()

    • Pop also returns the removed value: x = game.pop().

    • You can also pop by index: game.pop(3)

  • Delete by index:

    • del game[3]

    • or delete by slice: del game[1:5:2]

  • Join a list using the join method on the string type

    • print(', '.join(game))

  • Count number of elements using len:

    • len(game)


  • Tuples work exactly like a list, but are immutable.

  • For example, you can’t append.

8.3 Dict

  • syntax:

animals = {'kitten': 'meow', 'puppy': 'ruff!', 
           'lion': 'grrr', 'giraffe': 'I am a giraffe!', 
           'dragon': 'rawr' }

or

animals = dict(kitten = 'meow', puppy = 'ruff!', 
               lion = 'grrr', giraffe = 'I am a giraffe!', 
               dragon = 'rawr')
  • parse as: for x in o: print(f'{x}: {o[x]}')

  • keys must be immutable (strings and numbers can always be keys)

  • items method returns key-value pairs

    • for k, v in animals.items(): more readable than above

  • keys method returns only keys

    • for k in animals.keys():

  • values method returns only values

    • for v in animals.values():

  • to return the value at a key, animals['lion']

    • can assign a value, animals['lion'] - 'I am a lion'

  • add new value: animals['monkey'] = 'haha'

  • search for key using 'found!' if 'lion' in animals else 'nope!'

  • if you don’t know if a key exists, you can conditionally get value using the get method: animals.get('godzilla')

8.4 Sets

a = set("We're gonna need a bigger boat.")
b = set("I'm sorry, Dave. I'm afraid I can't do that.")
  • These contain an unordered list of the unique characters in each string. No duplicates in sets.

  • you can sort as print(sorted(a)


  • To check for members that are in a but not in b: a - b

  • Union - in set a or b: a | b

  • Intersection - in set a and b: a & b

  • In A or B but not both: a ^ b

8.5 Comprehension

  • List created based on another list or iterator

  • seq = [x * 2 for x in range(10)]

  • seq = [x for x in range(10) if x % 3 != 0]

    • if allowed only after for

  • seq = [(x, x**2) for x in range(10)] (tuples)

  • seq = [round(pi, x) for x in range(10)] (functions)

  • seq = {x: x**2 for x in range(10)} (dictionary)

  • seq = {x for x in 'superduper' if x not in 'pd'} (set)

8.6 Mixed

  • Examples:

r = range(11)
l = [1, 'two', 3, {'4': 'four' }, 5]
t = ('one', 'two', None, 'four', 'five')
s = set("It's a bird! It's a plane! It's Superman!")
d = dict(one = r, two = l, three = s)
mixed = [l, r, s, d, t]