Main.Tuples History
Hide minor edits - Show changes to markup
March 23, 2010, at 11:12 PM MST
by -
Added lines 1-47:
(:source lang=python:)
"""tuples http://openbookproject.net/thinkcs/python/english2e/ch11.html#tuples-and-mutability """
- A tuple is like a list - it is a sequence of elements that can be accessed
- by their index.
- The difference - tuples are immutable
- A tuple can be defined using syntax similar to a list, with
- parentheses replacing square brackets:
tup = (1, 5, 10, 20)
- it is possible to eliminate the parentheses:
tup = 1, 5, 10, 20
- It is slightly tricky to create a tuple with a single element:
tup = 5,
- or
tup = (5,)
- tuples support the same indexing and slice operations as strings and lists
- like lists you can't modify a tuple:
tup = ('a', 'b', 'c', 'd', 'e')
- now try modifying tup[0]:
tup[0] = 'z'
- when returning multiple objects from a function, you typically do so
- as a tuple:
def myfunc() :
return 3,5,10
- you can now call this function as:
x,y,z = myfunc()
- or
tup = myfunc()
- and check that this is indeed a tuple:
print type(tup)
- tuples are particularly useful as keys for dictionaries
(:sourceend:)
