Home » Blog » Pythonlearn:resources-week10

Pythonlearn:resources-week10

Lecture Notes

Tuples

Tuples are a sequence that behave much like a list, except:

  • Tuples are immutable (cannot be altered)
  • displayed surrounded by parentheses ‘(,)’ rather than brackets ‘[,]’
  • surrounding by parenthesis is just visual help; Comma is what makes tuple type
  • cannot sort, append, reverse, reorder, etc
  • can only: count and index

Tuples are more efficient, they use less processing time since fewer operations are possible.

Tuples are great for “temporary variables” because they are fast and easy to work with.

Tuples can be placed on the left-hand side on an assignment statement, the parentheses can even be omitted.

(x,y) = (4, 'fred')
print y
fred

Tuples and Dictionaries

The ‘items()’ method in dictionaries returns a list of tuples (key, value).

Tuples are Comparable
The contents of a tuple can be compared and evaluated, running left to right through the listed variables. <, >, <=, >=, ==

~~Applying the sorted() function (which takes a sequence as a parameter and returns a sorted sequence) to a dictionary yields a list of its keys in sorted order; e.g.:

>>> c = {'a': 10, 'c': 22, 'b': 1, 'f': 22}
>>> sorted(c)
['a', 'b', 'c', 'f']

We can print the key:value pairs in order by key by:

>>> for k in sorted(c):
...     print k, c[k]
...     
a 10
b 1
c 22
f 22

We can build a list of the key:value pairs in order by key by appending each pair as a tuple to an initially empty list:

>>> csorted = []
>>> for k in sorted(c): # if c is dictionary, it CAN'T be sorted...
...     csorted.append((k, c[k]))
... 
>>> csorted
[('a', 10), ('b', 1), ('c', 22), ('f', 22)]

The same thing can be achieved using a tuple (with or without parentheses) as the for-loop control and building a list of tuples from c.items(), then sorting it:

>>> for k, v in c.items():
...     csorted.append((k, v))
... 
>>> csorted
[('a', 10), ('c', 22), ('b', 1), ('f', 22)]
>>> sorted(csorted)
[('a', 10), ('b', 1), ('c', 22), ('f', 22)]
>>> csorted = sorted(csorted)
>>> csorted
[('a', 10), ('b', 1), ('c', 22), ('f', 22)]

Since the items() method for a dictionary returns a list of its key:value pairs as tuples:

>>> c.items()
[('a', 10), ('c', 22), ('b', 1), ('f', 22)]

we could just sort c.items() instead of building a new list of tuples “by hand” first:

>>> sorted(c.items())
[('a', 10), ('b', 1), ('c', 22), ('f', 22)]

But if we want to sort the dictionary, c, by value instead of key we need to build the list of value:key pairs as tuples by hand (by reversing the value and key (v, k)), then sort that list:

>>> tmp = list()
>>> for k, v in c.items():
...     tmp.append( (v, k) )
... 
>>> print tmp
[(10, 'a'), (22, 'c'), (1, 'b'), (22, 'f')]
>>> tmp.sort(reverse=True)
>>> print tmp
[(22, 'f'), (22, 'c'), (10, 'a'), (1, 'b')] 

When sorting by value and there are duplicate values, the second item in the tuple defines the order of the duplicates.

c = {'a':10, 'b':1, 'c':22, 'f':22}
tmp = list()
for k, v in c.items() :
    tmp.append( (v, k) )

print tmp
#[(10, 'a'), (22, 'c'), (1, 'b'), (22, 'f')]
tmp.sort(reverse=True)
print tmp
#[(22, 'f'), (22, 'c'), (10, 'a'), (1, 'b')]  
#because 'f' comes  before 'c' when sorting in reverse order.

List Comprehension

List comprehension (represented by [,]) creates a dynamic list.

print sorted( [ (v,k) for k,v in c.items() ] )

The above can sort a list of items in a dictionary(c) by the value. By first reversing the tuples (v,k) and then sorting it.

Chapter 10 Exercises

The above page is intended as a place for students to work out solutions and answers to the exercises from the textbook. Please do not post answers to exercises that are actual graded assignments.

More Resource Topics

Add resources for this chapter to this page..

https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions