Main.Tuples History

Hide minor edits - Show changes to markup

March 23, 2010, at 11:12 PM MST by 71.196.160.210 -
Added lines 1-47:

(:source lang=python:)

"""tuples http://openbookproject.net/thinkcs/python/english2e/ch11.html#tuples-and-mutability """

  1. A tuple is like a list - it is a sequence of elements that can be accessed
  2. by their index.
  3. The difference - tuples are immutable
  4. A tuple can be defined using syntax similar to a list, with
  5. parentheses replacing square brackets:

tup = (1, 5, 10, 20)

  1. it is possible to eliminate the parentheses:

tup = 1, 5, 10, 20

  1. It is slightly tricky to create a tuple with a single element:

tup = 5,

  1. or

tup = (5,)

  1. tuples support the same indexing and slice operations as strings and lists
  2. like lists you can't modify a tuple:

tup = ('a', 'b', 'c', 'd', 'e')

  1. now try modifying tup[0]:

tup[0] = 'z'

  1. when returning multiple objects from a function, you typically do so
  2. as a tuple:

def myfunc() :

    return 3,5,10
  1. you can now call this function as:

x,y,z = myfunc()

  1. or

tup = myfunc()

  1. and check that this is indeed a tuple:

print type(tup)

  1. tuples are particularly useful as keys for dictionaries

(:sourceend:)