A tuples groups multiple (possiblely with different types) objects. They can be compared to (static) structures of other languages.
In [ ]:
print(type(()))
In [ ]:
help(())
And some timing ... :-)
In [ ]:
!python -m timeit "x = (1, 'a', 'b', 'a')"
In [ ]:
a = (1, 'a', 'b', 'a')
In [ ]:
a.count('a')
In [ ]:
a.index('b')
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[:])
In [ ]:
def return_tuple():
return (1, 'a', 2)
print(return_tuple())
In [ ]:
a = 1; b = 2
print(a, b)
(a, b) = (b, a)
print(a, b)
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)