# Exploring Lists and Dicts in Python¶

Let's do some timing tests to explore using lists and dicts.

First, let's import some timing code:

In [1]:
import time


And you can use it like this:

In [2]:
time.time()

Out[2]:
1392049686.71137

So, time.time() returns a number representing the current time.

We could use it to see how long something takes:

In [3]:
time.time() - time.time()

Out[3]:
-6.103515625E-05
Let's write a function to see how long something takes:
In [4]:
def timeit(f):
start = time.time()
f()
print(time.time() - start)


We can use it like so:

In [5]:
def addem():
L = []
for i in range(10000000):
L.append(i)


1.65251922607


We can use some advanced features of Python to make it so that we can pass values to the function $f$ that we are timing.

In [6]:
def timeit(f, *args, **kwargs):
start = time.time()
f(*args, **kwargs)
print(time.time() - start)

In [7]:
def addem(count):
L = []
for i in range(count):
L.append(i)


0.00413513183594

In [8]:
timeit(addem, 1000)

0.000480651855469

In [9]:
timeit(addem, 1000)

0.000282287597656


Does the list L contain 523? Yes, because we know it contains all numbers between 0 and 999 inclusive. In fact a good name for addem might be range because it does the same thing.

Let's make addem add random numbers:

In [1]:
import random

In [11]:
random.random()

Out[11]:
0.201483504940515
In [12]:
random.randint(0, 3)

Out[12]:
3

What does random.randint(start, stop) do?

Let's change addem so that it adds a certain number of random numbers, between 0 and maxint:

In [2]:
def addem(count, maxint):
L = []
for i in range(count):
L.append(random.randint(0, maxint))
return L

In [14]:
addem(100, 10)

Out[14]:
[6, 4, 5, 8, 8, 1, 4, 7, 10, 4, 10, 2, 3, 0, 1, 5, 9, 2, 5, 7, 3, 3, 8, 7, 2, 5, 2, 2, 8, 3, 0, 8, 4, 9, 7, 7, 3, 9, 2, 7, 9, 10, 4, 4, 3, 6, 3, 9, 3, 7, 9, 7, 10, 9, 8, 8, 10, 6, 1, 1, 8, 5, 5, 2, 5, 10, 9, 9, 7, 6, 1, 10, 10, 9, 8, 6, 4, 9, 10, 5, 5, 6, 1, 7, 6, 5, 3, 1, 4, 7, 9, 5, 2, 7, 6, 9, 0, 6, 7, 8]

Now, let's write a function that will search for a number:

In [4]:
def find(list, item):
count = 0
for i in list:
if item == i:
return count
count += 1
return -1

In [16]:
def f1():
print("hi")

def f2():
return "hi"

In [17]:
print(f2())

hi

In [18]:
f1()

hi

In [19]:
list = addem(1000, 1000)

In [5]:
x = 10000
list = addem(x, x)
total = 0
for i in range(x):
if find(list, i) >= 0:
total += 1
print(total/x)

0.6312


How long does it take to find if something is in a list? in a dict?

# Designing your own Classes¶

How does something like list and dict come about?

In [ ]: