Python: Tuple [Data Type]

Tuple is an immutable and ordered collection of items. A tuple is similar to a list, but the items can not be changed, once the tuple is created.

Tuple Capabilities

Here is what a Tuple in Python can and can’t do-

Tuple can do

Can contain different types of data at the same time.
Can define an empty Tuple(without any item).
Multiple tuples defined with the same items, in the same sequence, refer to the same tuple object.
Supports fixed size. Once created, the size can not be changed.
Can be nested with other tuples or any other data structure(like list, dictionary, set).
List, dictionary, set, etc. nested in a tuple, can be changed later.
Can be used as a key in dictionary.

Tuple can not do

Can not be changed once defined.
Internally Tuple does not store items. Instead, the items are stored separately in memory, and Tuple just holds the reference to those item objects.

Define a Tuple

Let’s see how we can define a tuple-

Method #1: Standard Tuple Definition

Separate the items with a comma(,) and enclose the whole thing with parentheses, to define a Tuple. Check the example below-

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

print(big_box_tpl)
print(type(big_box_tpl))
print(len(big_box_tpl))
print(dir(big_box_tpl))
Python

Output:

('First', 'Second', 'test', 123, 456, 789, 'last')

<class 'tuple'>

7

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
Plaintext

NOTE

We can define an empty tuple by using just empty parentheses-

big_box_tpl = ()

print(big_box_tpl)
print(type(big_box_tpl))
print(len(big_box_tpl))
Python

Output:

()
<class 'tuple'>
0
Plaintext

WARNING

If we try to change any item of a tuple, it will throw an error-

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

big_box_tpl[1] = "changed"
Python

Output:

Traceback (most recent call last):
  File "tuple.py", line 3, in <module>
    big_box_tpl[1] = "changed"
    ~~~~~~~~~~~^^^
TypeError: 'tuple' object does not support item assignment
Plaintext

Method #2: Just Comma Separating Items

We can define a tuple by just separating items with commas.

big_box_tpl = "Big", "Box", "Code"

print(big_box_tpl)
print(type(big_box_tpl))
print(len(big_box_tpl))
Python

Output:

Note that, the tuple is printed as enclosed in parentheses. Though we defined it without parentheses, but it is internally represented with parentheses.

('Big', 'Box', 'Code')

<class 'tuple'>

3
Plaintext

NOTE

If we want to define a tuple with only one item, without using parenthesis- then we have to add a comma at the end.

big_box_tpl = "Big",

print(big_box_tpl)
print(type(big_box_tpl))
print(len(big_box_tpl))
Python

Output:

('Big',)
<class 'tuple'>
1
Plaintext

Object Referencing

Tuples do not store the items, but store the reference object. When a tuple is created, it stores the references of the items, not the value of the items.

Case #1

The items in tuple, store the reference of individual item objects. The same item in multiple tuples has the same object reference, as those refer to the same object in memory.

i1 = 100
s1 = 'bigboxcode'
f1 = 99.99

print(f"i1 => value: {i1} || type: {type(i1)} || id: {id(i1)}")
print(f"s1 => value: {s1} || type: {type(s1)} || id: {id(s1)}")
print(f"f1 => value: {f1} || type: {type(f1)} || id: {id(f1)}")


big_box_tpl = ("abc", 100, "bigboxcode", 99.99)

print(f"big_box_tpl[0] => value: {big_box_tpl[0]} || type: {type(big_box_tpl[0])} || id: {id(big_box_tpl[0])}")
print(f"big_box_tpl[1] => value: {big_box_tpl[1]} || type: {type(big_box_tpl[1])} || id: {id(big_box_tpl[1])}")
print(f"big_box_tpl[2] => value: {big_box_tpl[2]} || type: {type(big_box_tpl[2])} || id: {id(big_box_tpl[2])}")
print(f"big_box_tpl[3] => value: {big_box_tpl[3]} || type: {type(big_box_tpl[3])} || id: {id(big_box_tpl[3])}")
Python

Output:

Value from tuple has the same object reference as the previously defined individual values.

i1 => value: 100 || type: <class 'int'> || id: 140479784373584
s1 => value: bigboxcode || type: <class 'str'> || id: 140479783246128
f1 => value: 99.99|| type: <class 'float'> || id: 140479782931728

big_box_tpl[0] => value: abc || type: <class 'str'> || id: 140479783191088

big_box_tpl[1] => value: 100 || type: <class 'int'> || id: 140479784373584
big_box_tpl[2] => value: bigboxcode || type: <class 'str'> || id: 140479783246128
big_box_tpl[3] => value: 99.99 || type: <class 'float'> || id: 140479782931728
Plaintext

Here is how the referencing looks under the hood-

Tuple item referencing
Tuple item referencing

Case #2

Multiple Tuples defined with the same values, in the same sequence refer to the same object.

big_box_tpl = ("abc", 100, "bigboxcode", 99.99)

print(f"big_box_tpl => value: {big_box_tpl} || type: {type(big_box_tpl)} || id: {id(big_box_tpl)}")

# Define another tuple with the same values
big_box_tpl1 = ("abc", 100, "bigboxcode", 99.99)

print(f"big_box_tpl1 => value: {big_box_tpl1} || type: {type(big_box_tpl1)} || id: {id(big_box_tpl1)}")

# Assign big_box_tpl1 to big_box_tpl2
big_box_tpl2 = big_box_tpl1

print(f"big_box_tpl2 => value: {big_box_tpl2} || type: {type(big_box_tpl2)} || id: {id(big_box_tpl2)}")

# Create tuple with same values, but in different sequence
big_box_tpl3 = (100, "abc", 99.99, "bigboxcode")

print(f"big_box_tpl3 => value: {big_box_tpl3} || type: {type(big_box_tpl3)} || id: {id(big_box_tpl3)}")
Python

Output:

big_box_tpl => value: ('abc', 100, 'bigboxcode', 99.99) || type: <class 'tuple'> || id: 139660434219280
big_box_tpl1 => value: ('abc', 100, 'bigboxcode', 99.99) || type: <class 'tuple'> || id: 139660434219280
big_box_tpl2 => value: ('abc', 100, 'bigboxcode', 99.99) || type: <class 'tuple'> || id: 139660434219280

big_box_tpl3 => value: (100, 'abc', 99.99, 'bigboxcode') || type: <class 'tuple'> || id: 139660434224560
Plaintext

Item Indexing in Tuple

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

print(big_box_tpl[0])
print(big_box_tpl[2])
print(big_box_tpl[6])
print(big_box_tpl[-1])
Python

Output:

First
test
last
last
Plaintext

Nesting in Tuple

We can add other tuples, lists, dictionaries, etc. to a Tuple. The behavior of those lists, dictionaries and other data types will remain the same.

Define Nested Items

Add other data types directly into the Tuple.

big_box_tpl = (
    1,
    2,
    3,
    ("abc", "def"),
    ["big", "box", "code"],
    {
        "site": "BigBoxCode",
    },
    {
        "first item",
        "second ite",
    },
)

print(big_box_tpl)
Python

Output:

(1, 2, 3, ('abc', 'def'), ['big', 'box', 'code'], {'site': 'BigBoxCode'}, {'first item', 'second ite'})
Plaintext

We can also separately define the lists, dictionaries, sets and then add it to the tuple-

tpl1 = ("abc", "def")
list1 = ["big", "box", "code"]
dict1 = {
    "site": "BigBoxCode",
}

set1 = {
    "first item",
    "second ite",
}

big_box_tpl = (1, 2, 3, tpl1, list1, dict1, set1)

print(big_box_tpl)
Python

Output:

(1, 2, 3, ('abc', 'def'), ['big', 'box', 'code'], {'site': 'BigBoxCode'}, {'first item', 'second ite'})
Plaintext

Change Items in Nested Tuple

The behavior of a list, or dictionary, or other data type remains the same even when it is nested inside a Tuple. We can still change those items.

tpl1 = ("abc", "def")
list1 = ["big", "box", "code"]
dict1 = {
    "site": "BigBoxCode",
}

set1 = {
    "first item",
    "second item",
}

big_box_tpl = (1, 2, 3, tpl1, list1, dict1, set1)

print(big_box_tpl)

# Change the list
list1.append("New item 1")

# Change dictioary
dict1["url"] = "https://bigboxcode.com"
dict1["github"] = "github.com/webhkp/bigboxcode"

# Change the set
set1.add("Another item")
set1.add(999.99)

print(big_box_tpl)
Python

Output:

(1, 2, 3, ('abc', 'def'), ['big', 'box', 'code'], {'site': 'BigBoxCode'}, {'first item', 'second item'})

(1, 2, 3, ('abc', 'def'), ['big', 'box', 'code', 100], {'site': 'BigBoxCode', 'github': 'github.com/webhkp/bigboxcode'}, {'first item', 'second item', 999.99})
Plaintext

The same thing happens when we define those lists, dictionaries and sets separately-

tpl1 = ("abc", "def")
list1 = ["big", "box", "code"]
dict1 = {
    "site": "BigBoxCode",
}

set1 = {
    "first item",
    "second item",
}

big_box_tpl = (1, 2, 3, tpl1, list1, dict1, set1)

print(big_box_tpl)

# Change the list
list1.append("New item 1")

# Change dictioary
dict1["url"] = "https://bigboxcode.com"
dict1["github"] = "github.com/webhkp/bigboxcode"

# Change the set
set1.add("Another item")
set1.add(999.99)

print(big_box_tpl)
Python

Output:

(1, 2, 3, ('abc', 'def'), ['big', 'box', 'code'], {'site': 'BigBoxCode'}, {'first item', 'second item'})

(1, 2, 3, ('abc', 'def'), ['big', 'box', 'code', 'New item 1'], {'site': 'BigBoxCode', 'url': 'https://bigboxcode.com', 'github': 'github.com/webhkp/bigboxcode'}, {'Another item', 'first item', 999.99, 'second item'})
Plaintext

Looping through Tuple

Case #1

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

for item in big_box_tpl:
    print(item)
Python

Output:

First
Second
test
123
456
789
last
Plaintext

Case #2

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

# Start from index 0
item_index = 0

while item_index < len(big_box_tpl):
    print(f"Index: {item_index} || Item value: {big_box_list[item_index]}")
    
    # Increase the index by 1
    item_index += 1
Python

Output:

First
Second
test
123
456
789
last
Plaintext

Tuple Concatenation

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

tuple2 = ("new 1", "new 2", "new 3")

print(big_box_tpl + tuple2)
Python

Output:

('First', 'Second', 'test', 123, 456, 789, 'last', 'new 1', 'new 2', 'new 3')
Plaintext

Check Item Existence

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

print("First" in big_box_tpl)
print(123 in big_box_tpl)

print("123" in big_box_tpl)
print("Unknown" in big_box_tpl)
Python

Output:

True
True

False
False
Plaintext

Slicing a Tuple

big_box_tpl = ("First", "Second", "test", 123, 456, 789, "last")

print(big_box_tpl[0:4])
print(big_box_tpl[:4])
print(big_box_tpl[4:])
print(big_box_tpl[0:-1])
Python

Output:

('First', 'Second', 'test', 123)
('First', 'Second', 'test', 123)
(456, 789, 'last')
('First', 'Second', 'test', 123, 456, 789)
Plaintext

Named Tuple

A named tuple is similar to a tuple. But in a named tuple, we can access the items by name(also by index).

Python Named Tuple
Python Named Tuple

Use the “namedtuple” function from “collections” module, to create a named tuple. The following parameters are used to define the named tuple-

  • First param – typename : name of the type
  • Second param – field_names : list of field names separated by space

Here we are creating a named tuple with named “Product” which has fields – “name”, “mode”, “color”, “weight”.

import collections

Product = collections.namedtuple('Product', 'name model color weight')

product_one = Product("Sonic Wireless Headphones", "SWH-30G21", "Black", "0.5lbs")

print(Product)
print(product_one)
Python

Output:

<class '__main__.Product'>

Product(name='Sonic Wireless Headphones', model='SWH-30G21', color='Black', weight='0.5lbs')
Plaintext

We can use any data type as a value for the fields. The field can be of another named tuple.

Here we have used “Price” as another named tuple, which defines product price with fields – “original_price”, “discount”, “final_price”.

import collections

Product = collections.namedtuple('Product', 'name model color weight price')
Price = collections.namedtuple('Price', 'original_price discount final_price')

product_one = Product("Sonic Wireless Headphones", "SWH-30G21", "Black", "0.5lbs", Price(99.99, 9.00, 90.00))

print(Product)
print(product_one)
Python

Output:

<class '__main__.Product'>

Product(name='Sonic Wireless Headphones', model='SWH-30G21', color='Black', weight='0.5lbs', price=Price(original_price=99.99, discount=9.0, final_price=90.0))
Plaintext

We can access the fields from “Product” and from “Price” using the field names-

import collections

Product = collections.namedtuple('Product', 'name model color weight price')
Price = collections.namedtuple('Price', 'original_price discount final_price')

product_one = Product("Sonic Wireless Headphones", "SWH-30G21", "Black", "0.5lbs", Price(99.99, 9.00, 90.00))

print(product_one.name)
print(product_one.model)
print(product_one.price.final_price)
Python

Output:

Sonic Wireless Headphones
SWH-30G21
90.0
Plaintext

We can also access those field using index of the field, like below-

import collections

Product = collections.namedtuple('Product', 'name model color weight price')
Price = collections.namedtuple('Price', 'original_price discount final_price')

product_one = Product("Sonic Wireless Headphones", "SWH-30G21", "Black", "0.5lbs", Price(99.99, 9.00, 90.00))

print(product_one[0])
print(product_one[1])
print(product_one[2])
print(product_one[3])
print(product_one[4])
print(product_one[4][0])
Python

Output:

Sonic Wireless Headphones
SWH-30G21
Black
0.5lbs
Price(original_price=99.99, discount=9.0, final_price=90.0)
99.99
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.