×

By the end of this chapter, you should be able to:

- Distinguish between the different types of imports
- Give examples of advanced data types provided by the
`collections`

module

Now that you know how to import, let's examine a few useful modules:

The `random`

module is quite useful for generating random values of all kinds:

import random random.randint(1,10) # generate a number between 1 and 10 random.randrange(4) # generate between 0 and 3 random.random() # generate a number between 0 and 1

Here's an example pulling just a single function, the `choice`

function, which grabs an element at random from a list:

from random import choice as c c([1,2,3,4,5]) # run this line several times, you should see different elements get returned

The `math`

module provides access to many mathematical functions, including helpers for rounding, constants like `e`

and `pi`

, and trigonometric functions.

import math math.e # 2.718281828459045 math.pi # 3.141592653589793 math.floor(2.2) # 2 math.ceil(2.2) # 3 math.sqrt(16) # 4 math.pow(2,10) # 1024.0

This is a built in module that provides alternatives to Python's built-in containers like `dict`

, `list`

, `set`

, and `tuple`

. Take a look at each one of these and see what they do.

from collections import Counter l = [1,1,2,3,3,4,4,5,5] Counter(l) # see what this returns! string = "aweosakjdsaldwjdwq" Counter(string) s = 'this is such a nice nice nice thing that is nice!' c = Counter(s.split()) # Counter({'a': 1, # 'is': 2, # 'nice': 3, # 'nice!': 1, # 'such': 1, # 'that': 1, # 'thing': 1, # 'this': 1}) c.items() # list of element,count tuples c.clear() # clear all values c.values() # see all values

from collections import defaultdict regular_dict = dict(first=1) regular_dict['first'] # 1 regular_dict['second'] # KeyError! def default_value(): return "nothing" d = defaultdict(default_value) d['nice'] = "cool" d['nice'] # "cool" d['whoaaa'] # "nothing"

An ordered dictionary remembers the order in which key-value pairs were added.

from collections import OrderedDict d = {} d['one'] = 1 d['two'] = 2 d['three'] = 3 d['four'] = 4 for k,v in d.items(): print(k,v) # no order! od = OrderedDict() od['one'] = 1 od['two'] = 2 od['three'] = 3 od['four'] = 4 for k,v in od.items(): print(k,v) # order!

from collections import namedtuple t = (1,2,3) t[1] = 2 Person = namedtuple('Person', 'first_name last_name fav_color') elie = Person('Elie', 'Schoppik', 'purple') elie.fav_color # 'purple'

When you're ready, move on to Debugging and Modules Exercises