Monday, July 16, 2018

Tuples


What are tuples?
----------------

- Tuples are another type of sequence in Python
- they are immutable
- they can be packed
- they can be unpacked to variables
- they can contain mutable objects
- lightweight compared to lists

Demo on how to use tuples
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
Ways on defining an empty tuple
and a tuple with only 1 element
>>> empty = ()
>>> singleton = 'hello',    # <-- comma="" note="" p="" trailing="">
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Packing and unpacking a tuple
>>> t = 23, 'grapes', 'linux'  # packing a tuple
>>> t
(23, 'grapes', 'linux')
>>>
>>> number, fruit, os = t  # unpacking a tuple
>>> number
23
>>> fruit
'grapes'
>>> os
'linux'
>>>
>>> number, fruit, os, car = t      # number of variables on the left side must match
Traceback (most recent call last):  # the number of elements on the right tuple
  File "", line 1, in
ValueError: not enough values to unpack (expected 4, got 3)
>>>
Tuples can be converted to list
and vice-versa
>>> secret_message = "hello world"
>>> list(secret_message)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(secret_message)
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
>>> list(tuple(list(secret_message)))
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> ''.join(list(tuple(list(secret_message))))
'hello world'
You can also do comparison
between tuples
>>> t1
(1, 5, 7.6)
>>> t2
(2, 8, 100)
>>>
>>> t1 < t2
True
>>>
>>> t1 > t2
False
You cannot delete a specific
element in a tuple but you can
delete all of them at once
>>> num = 600, 1, 5, 45.6
>>> num
(600, 1, 5, 45.6)
>>> del num[2]
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'tuple' object doesn't support item deletion
>>> del num
>>> num
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'num' is not defined
>>>
Other operations that can be done
on tuples
>>> len((1, 2, 3))  # length
3
>>> (1, 2, 3) + (4, 5, 6)  # addtion (concatenation)
(1, 2, 3, 4, 5, 6)
>>> ('Hi!',) * 4  # repetition
('Hi!', 'Hi!', 'Hi!', 'Hi!')
>>> 3 in (1, 2, 3)  # membership
True
>>> for x in (1,2,3) : print (x, end = ' ')  # iteration
...
1 2 3 >>>
>>>
Since tuples are also sequences,
you can do slice and index
operations against them
>>> T=('C++', 'Java', 'Python')
>>> T[2]
'Python'
>>> T[-2]
'Java'
>>> T[1:]
('Java', 'Python')
>>>
Other tuple functions
cmp(tuple1, tuple2)
len(tuple)
max(tuple)
min(tuple)
tuple(seq)

No comments:

Post a Comment