List - Dictionary - Tuples

What will be Covered?

  1. List
  2. Tuples
  3. Dictionary

Reference Documents

List

  • Stores elements one after another
  • It does not provide fast lookups. Finding an element is often slow. A search is required.
  • Elements can be easily added, looped over or sorted.

Create a List


In [ ]:
myList = []
myList = ["The", "earth", "revolves", "around", "sun"]

In [ ]:
myList[5]

In [ ]:
myList[4]

In [ ]:
myList[-1]

Typical List Operations


In [ ]:
L = []          # declare empty list
L.append(1.2)   # add a number 1.2
L.append('a')   # add a text
L.append(None)   # add a text
L[0] = 1.3      # change an item
len(L)          # length of list
x='a'
L.count(x)      # count the number of times x occurs
L.index(x)      # return the index of the first occurrence of x
L.remove(x)     # delete the first occurrence of x
L.reverse       # reverse the order of elements in the list
del L[1]        # delete an item

In [ ]:
# after all this what elements are left in L?
print L

Add Elements to a List


In [ ]:
myList.insert(0,"Yes")
len(myList)

In [ ]:
myList.append(["a", "true"])
len(myList)

In [ ]:
myList.extend(["statement", "for", "sure"])
print myList
len(myList)

Slice Elements from a List


In [ ]:
myList[0]

In [ ]:
myList[1:4]

In [ ]:
myList[:4]

In [ ]:
myList[-1]

In [ ]:
myList[:]

Search the Lists and find Elements


In [ ]:
# which element in the list is 'revolves'?
myList.index("revolves")

In [ ]:
# which element in the list is 'true'?
myList.index("true")

In [ ]:
myList.index(["a", "true"])

In [ ]:
"sun" in myList

In [ ]:
"true" in myList

Delete Elements from the List


In [ ]:
# Remove an element from the list
print myList
myList.remove("Yes")
print myList

In [ ]:
# To delete the last element of the list
myList.pop()
print myList

Python List Operators


In [ ]:
# Combine two lists
print myList
myList = myList + ["sure"]
print myList

In [ ]:
myList += ["."]
print myList

In [ ]:
# Repeat the list
myList *= 2
print myList

Assignment Create Object Reference


In [ ]:
x = [0,1,2]

In [ ]:
# y = x causes x and y to point to the same list
y = x
print y

In [ ]:
# Change to y also change x
y[1] = 6
print y
print x

In [ ]:
# re-assigning y to a new list decouples the two lists
y = [3, 4]

Problem 1

Consider the list:


In [ ]:
oldList = [[1,2,3],[4,5,6]]

Use operations on lists to manipulate oldList and create the list [[1,2],[4,6]]


In [ ]:
# your code goes here!

Tuples

  • Tuples are a sequence of objects just like lists.
  • Unlike lists, tuples are immutable objects
  • Tuples are faster than lists.
  • A good rule of thumb is to use list whenever you need a generic sequence

Examples


In [ ]:
l1=[1.2, 1.3, 1.4]       # list
t1=(1.2, 1.3, 1.4)       # tuple
t1=1.2, 1.3, 1.4         # may skip parenthesis

In [ ]:
l1[1]=0                  # ok
l1.sort()                # only
l1.append(0.0)           # for
l1.remove(1.2)           # lists
print l1

Tuple = constant list; items cannot be modified


In [ ]:
t1[1]=0                  # illegal

Tuples have no methods


In [ ]:
t1.sort()               # nope
t1.append(0.0)          # nuh-uh
t1.remove(1.2)          # not gonna do it

You can add two tuples to form a new tuple


In [ ]:
t2 = ('a', 'b')
t3 = t1+t2
print t3

Accessing Values in Tuples


In [ ]:
print "t3[0]:   ", t3[0]
print "t3[1:3]: ", t3[1:3]

Operations on Tuples


In [ ]:
print len(t3)

print "c" in t3

for x in t3:
    print x

Problem 2

Consider the tuple:


In [ ]:
julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")

Use tuple operations to manipulate the above tuple to get a new tuple:


In [ ]:
("Julia", "Roberts", 1967, "Eat Pray Love", 2010, "Actress", "Atlanta, Georgia")

In [ ]:

Dictionary

  • An array with with text indices (keys, even user-defined objects can be indices!)
  • Also called hash or associative array in other languages
  • Can store 'anything'
  • The text index is called key

Initializing a Dictionary


In [ ]:
d = {}    # empty dictionary

In [ ]:
value1 = 'Python BootCamp'
value2 = 2016
oxford = { 'key1' : value1, 'key2' : value2 }
oxford = dict(key1=value1, key2=value2)

In [ ]:
d['list']  = [1.2, 2.5]
d['tuple'] = 'a','b','c'
d['pi']    = 3.14159265359
print d

Common Operations


In [ ]:
d['pi']         # extract item corresp. to key 'mass’
d.keys()          # return copy of list of keys
len(d)            # the number of items
d.get('pi',1.0) # return 1.0 if 'mass' is not a key
d.has_key('pi') # does d have a key 'mass'?
d.values()        # return a list of all values in the dictionary
d.items()         # return list of (key,value) tuples
d.copy()          # create a copy of the dictionary
del d['pi']     # delete an item
d.clear()         # remove all key/value pair from the dictionary

Examples


In [ ]:
# create an empty dictionary using curly brackets 
record = {}
record['first'] = 'Jmes'
record['last'] = 'Maxwell'
record['born'] = 1831
print record

In [ ]:
# create another dictionary with initial entries
new_record = {'first': 'James', 'middle':'Clerk'}

In [ ]:
# now update the first dictionary with values from the new one
record.update(new_record)
print record

Problem 3

Consider the following dictionary


In [ ]:
ab = {'met_opt': '3',
      'met_grid_type': 'A',
      'do_timinterp_met': 'F',
      'mrnum_in': '1',
      'met_filnam_list': 'jan2004.list',
      'do_read_met_list': 'T',
      'do_cycle_met': 'F',
      'gwet_opt': '1',
      'mdt': '10800.0'
     }
  • Print the value associated with the key 'mdt'
  • Print the length of the dictionary
  • Add to the dictionary another key 'met_infile_num' with the corresponding value '16'
  • Print the length of the dictionary
  • Write a loop to only print all the keys
  • Wrute a loop to only print all the values
  • Write a loop to print on the same line each key and its correcponding value

In [ ]: