Python - Tuple

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.

Constructor

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

Empty

Empty tuples are constructed by an empty pair of parentheses;

empty = ()
len(empty)
0

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',)

From range

With range

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

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)

With a generator

With a generator

>>> tuple(2*i for i in range(3))
(0, 2, 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))

How to

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)

update/delete value(s)

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

concat

tup1 = (1, 2, 3)
tup2= (4, 5, 6)

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

Unpacking

Python - (Un)Packing

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

Comprehension

Unpacking

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

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)

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)}

Documentation / Reference


Powered by ComboStrap