Tuples: Python For Informatics: Exploring Information
Tuples: Python For Informatics: Exploring Information
Chapter 10
Unlike a list, once you create a tuple, you cannot alter its
contents - similar to a string
>>> x = [9, 8, 7]
>>> x[2] = 6
>>> print x
>>>[9, 8, 6]
>>>
>>> y = 'ABC'
>>> y[2] = 'D'
Traceback:'str'
object does
not support item
Assignment
>>>
>>> z = (5, 4, 3)
>>> z[2] = 0
Traceback:'tuple'
object does
not support item
Assignment
>>>
>>> d = dict()
>>> d['csev'] = 2
>>> d['cwen'] = 4
>>> for (k,v) in d.items():
...
print k, v
...
csev 2
cwen 4
>>> tups = d.items()
>>> print tups
[('csev', 2), ('cwen', 4)]
Using
sorted()
We can do this even
more directly using the
built-in function sorted
that takes a sequence as a
parameter and returns a
sorted sequence
fhand = open('romeo.txt')
counts = dict()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0 ) + 1
lst = list()
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse=True)
for val, key in lst[:10] :
print key, val
Summary
Tuple syntax
Immutability
Comparability
Sorting
Tuples in assignment
statements
Sorting dictionaries by
either key or value
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance (www.
dr-chuck.com) of the University of Michigan School of Information
and open.umich.edu and made available under a Creative
Commons Attribution 4.0 License. Please maintain this last slide
in all copies of the document to comply with the attribution
requirements of the license. If you make a change, feel free to
add your name and organization to the list of contributors on this
page as you republish the materials.
Initial Development: Charles Severance, University of Michigan
School of Information
Insert new Contributors and Translators here
...