Overview

  • Hour 1
    • Tuples
    • Dictionaries
    • Take Up Midterm
  • Hours 2 and 3
    • Work Time

Lists

  • A list is an object that contains multiple data items
  • Lists are mutable
  • Lists can be indexed and sliced
  • Lists have methods

Syntax

  • Square brackets
  • Commas as separators

In [33]:
number_list = [1, 2, 4, 8, 16, 32]
the_pythons = ["Graham", "Terry",  "Michael", "Eric", "Terry", "John"]
mixed = [1, "Terry", 4]

print (mixed)


[1, 'Terry', 4]

Tuple

  • A tuple is an immutable version of a list
  • Immutable means that the contents cannot change after creation

Syntax

  • Parentheses
  • Commas as separators

In [34]:
monty = ("Graham", "Terry",  "Michael", "Eric", "Terry", "John")

In [35]:
# the entire tuple
print (monty)


('Graham', 'Terry', 'Michael', 'Eric', 'Terry', 'John')

In [36]:
# one element at a time
for name in monty:
    print(name)


Graham
Terry
Michael
Eric
Terry
John

In [39]:
# indexing
print(the_pythons[2])

print(monty[2])


Michael
Michael

[] brackets or square brackets () parentheses {} curly braces or braces

Converting Between Lists and Tuples

list()
tuple()

In [7]:
# monty is the tuple, and the_pythons is a list
print (monty)
print (list(monty))


('Graham', 'Terry', 'Michael', 'Eric', 'Terry', 'John')
['Graham', 'Terry', 'Michael', 'Eric', 'Terry', 'John']

In [9]:
print (the_pythons)
print (tuple(the_pythons))


['Graham', 'Terry', 'Michael', 'Eric', 'Terry', 'John']
('Graham', 'Terry', 'Michael', 'Eric', 'Terry', 'John')

Why?

  • Performance
    • Tuples are faster
  • Safety
    • Can't be modified

Looking ahead: tuples can be keys in a dictionary, but lists can't


In [ ]:
# Safer than constants, because it is enforced by interpreter
CONVERSION_CONSTANT = 5/9

Dictionaries

  • A dictionary is a collection data structure. Each element in a dictionary has two parts: a key and a value. You use a key to locate a specific value.
  • Shorthand description: a dictionary is like a list, but instead of the index being a number, the index is any value, e.g. int, float, string, tuple, etc.
  • Think dictionaries and phone books

In [20]:
my_dict = {}
my_dict[3.14] = "pi"
my_dict["pi"] = 3.14159
my_dict[(1,2)] = "x,y coordinates"
my_dict[(2,3)] = "x,y coordinates"
print my_dict


{(1, 2): 'x,y coordinates', 'pi': 3.14159, (2, 3): 'x,y coordinates', 3.14: 'pi'}

In [40]:
my_dict[(1,2)] = [4, 5, 6, 7]
print my_dict


{(1, 2): [4, 5, 6, 7], 'pi': 3.14159, (2, 3): 'x,y coordinates', 3.14: 'pi'}

In [41]:
len(my_dict)


Out[41]:
4

In [14]:
phone_book = {"Graham":"555-111", 
              "Terry": "555-2222", 
              "Michael": "555-3333"}

Retrieving a Value from a Dictionary

dictionary[key]

In [15]:
phone_book


Out[15]:
{'Graham': '555-111', 'Michael': '555-3333', 'Terry': '555-2222'}

In [18]:
phone_book['Michael']


Out[18]:
'555-3333'

In [42]:
my_dict[(1,2)]


Out[42]:
[4, 5, 6, 7]

In [43]:
phone_book['Wanda']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-43-7a063856545e> in <module>()
----> 1 phone_book['Wanda']

KeyError: 'Wanda'

Testing for Value in a Dictionary


In [45]:
# Using 'in'

if "Michael" in phone_book:
    print phone_book["Michael"]


555-3333

In [46]:
# Using 'not in'

if "Wanda" not in phone_book:
    print("Fish don't need phone numbers")


Fish don't need phone numbers

Adding Elements to a Dictionary


In [49]:
print(phone_book)

# Eric, Terry, John

phone_book["Eric"] = "555-4444"
phone_book["Terry"] = "555-5555"
phone_book["John"] = "555-6666"


{'Michael': '555-3333', 'John': '555-6666', 'Graham': '555-111', 'Eric': '555-4444', 'Terry': '555-5555'}

Deleting Elements

del dictionary[key]

In [50]:
del phone_book["John"]

In [51]:
print(phone_book)


{'Michael': '555-3333', 'Graham': '555-111', 'Eric': '555-4444', 'Terry': '555-5555'}

Putting it together

  • Test for presence of key before deletion

In [53]:
if 'Michael' in phone_book:
    del phone_book['Michael']

print(phone_book)


{'Graham': '555-111', 'Eric': '555-4444', 'Terry': '555-5555'}

In [54]:
if '555-4444' in phone_book:
    print ("Can match values too!")

Iterating over a Dictionary


In [55]:
for name in phone_book:
    print (name, phone_book[name])


('Graham', '555-111')
('Eric', '555-4444')
('Terry', '555-5555')

Dictionary Methods


In [56]:
phone_book.items()


Out[56]:
[('Graham', '555-111'), ('Eric', '555-4444'), ('Terry', '555-5555')]

In [57]:
phone_book.keys()


Out[57]:
['Graham', 'Eric', 'Terry']

In [58]:
phone_book.values()


Out[58]:
['555-111', '555-4444', '555-5555']

In [59]:
if '555-4444' in phone_book.values():
    print("We can match values too")


We can match values too

Midterm Discussion


In [62]:
even = False
if even = True: 
    print("It is even!")


  File "<ipython-input-62-f4a5eccef0b1>", line 2
    if even = True:
            ^
SyntaxError: invalid syntax

In [63]:
154 >= 300 != False


Out[63]:
False

In [71]:
def is_equal(t1, t2):
#    return t1 == t2
    return t1.sort() == t2.sort()

list1 = ["name", "age", "temp"]
list2 = ["name", "temp", "age"]

if is_equal(list1, list2):
    print("Same!")
else:
    print ("Different!")


Same!