Tuples in Python

✓ Tuple – A tuple is a sequence of values, and tuple are immutable.

>>> t = 'a', 'b', 'c', 'd', 'e'
>>> t = ('a', 'b', 'c', 'd', 'e')

>>> print tuple('lupins')
('l', 'u', 'p', 'i', 'n', 's')

>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
>>> print t[1:3]
('b', 'c')

✓ Tuples as return values

#Built-in function divmod takes two arguments and returns a tuple of two values
>>> t = divmod(7, 3)
>>> print t
(2, 1)

✓ Variable-length argument – Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple.

def printall(*args):
    print args
>>> printall(1, 2.0, '3')
(1, 2.0, '3')

>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1
>>> divmod(*t)
(2, 1)

✓ Lists and Tuples

>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]

def has_match(t1, t2):
    for x, y in zip(t1, t2):
        if x == y:
        return True
    return False

✓ Dictionaries and tuples – Dictionaries’ items method is used to create a list of tuples

>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]

>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}

>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s