Table of Contents

1. Tuples

A tuples groups multiple (possiblely with different types) objects. They can be compared to (static) structures of other languages.

1.1 Tuples are (as the rest of elements of Python) objects


In [ ]:
print(type(()))

In [ ]:
help(())

1.2. Tuple definition

And some timing ... :-)


In [ ]:
!python -m timeit "x = (1, 'a', 'b', 'a')"

In [ ]:
a = (1, 'a', 'b', 'a')

1.3. Counting ocurrences in tuples


In [ ]:
a.count('a')

1.4. Searching for an item in a tuple


In [ ]:
a.index('b')

1.5. Slicing in tuples


In [ ]:
a

In [ ]:
a[2] # The 3-rd item

In [ ]:
a[2:1] # Extract the tuple from the 2-nd item to the 1-st one

In [ ]:
a[2:2] # Extract from the 2-nd item to the 2-nd item

In [ ]:
a[2:3] # Extract from the 2-nd item to the 3-rd one

In [ ]:
a[2:4] # Extract one item more

In [ ]:
a[1:] # Extract from the 1-st to the end

In [ ]:
a[:] # Extract all items (a==a[:])

1.6. Functions can return tuples


In [ ]:
def return_tuple():
    return (1, 'a', 2)
print(return_tuple())

1.7. Swapping pairs with tuples is fun!


In [ ]:
a = 1; b = 2
print(a, b)
(a, b) = (b, a)
print(a, b)

1.8. Tuples are inmutable

They can not grow:


In [ ]:
a = (1, 'a')
print(id(a),a)

In [ ]:
a += (2,) # This creates a new instance of 'a'
print(id(a),a)

... or be changed:


In [ ]:
a[1] = 2

Tuples are inmutable!


In [ ]:
a = 1; b = 2
print('"a" is in', id(a))
t = (a, b)
print('"t" is in', id(t), 'and contains', t)
a = 3
print('"a" is in', id(a))
print('"t" is in', id(t), 'and contains', t)