Python - Tuple

> Procedural Languages > Python > Python - Data Type

1 - About

Tuples are:

  • an ordered sequence of elements, just like lists.
  • immutable so they can be elements of sets
  • but they can contain mutable objects.
Advertising

3 - Constructor

3.1 - Basic

A tuple consists of a number of values separated by commas

t = 12345, 54321, 'hello!'
t = (1,2,3)  # ordinary parentheses can be used to define a tuple

3.2 - Empty

Empty tuples are constructed by an empty pair of parentheses;

empty = ()
len(empty)
0

3.3 - One item

A tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

singleton = 'hello',    # <-- note trailing comma
len(singleton)
1
singleton
('hello',)
Advertising

3.4 - From range

With range

>>> tuple(range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

3.5 - From a list or set

With a list or a set

>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple({1,2,3})
(1, 2, 3)

3.6 - With a generator

With a generator

>>> tuple(2*i for i in range(3))
(0, 2, 4)

4 - Nested

Tuple may be nested

t = (12345, 54321, 'hello!')
u = t, (1, 2, 3, 4, 5) # Tuples may be nested:
u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

5 - How to

5.1 - get value(s) (indexing and slicing)

with indexing and slicing

tup = (1, 2, 3, 4, 5, 6, 7 )
 
print "tup[0]: ", tup[0] # indexing
print "tup[1:5]: ", tup[1:5] # slicing
tup[0]:  1
tup[1:5]:  (2, 3, 4, 5)
Advertising

5.2 - update/delete value(s)

tuples are immutable. You cannot change/delete a value. You have to create a new tuple.

5.3 - concat

tup1 = (1, 2, 3)
tup2= (4, 5, 6)
 
print "Concat Tup: ", tup1 + tup2
Concat Tup:  (1, 2, 3, 4, 5, 6)

5.4 - Unpacking

Python - (Un)Packing

>>> (a,b) = (1,2)
>>> a
1
>>> b
2

6 - Comprehension

6.1 - Unpacking

>>> (y for (x,y) in [(1,'A'),(2,'B'),(3,'C')] )
['A', 'B', 'C']

6.2 - Generator

Comprehension cannot be used to create tuple. The below statement is not a comprehension but a generator.

>>> (i for i in range(10))
<generator object <genexpr> at 0x02A1F350>

However, a comprehension can be written over a generator instead of over a list or set or tuple.

And the constructor (set(),list(),tuple()) transform a generator into a set or list or tuple.

>>> tuple(i for i in range(10))
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

6.3 - All tuple pairs in a list

>>> myList=[1,2,3,4]
>>> {(myList[j], myList[i]) for j in range(len(myList)) for i in range(j,len(myList)) if i != j}
{(1, 2), (1, 3), (1, 4), (2, 3), (3, 4), (2, 4)}

7 - Documentation / Reference