Tuples and namedtuple — Python
I did not know tuples were more than a data structure with brackets that are usually used in return statement. Tuples are quite a powerful data structure. We’ll be looking into Tuples and Python’s namedtuple()
factory function from collections
library with examples to illustrate.
Tuple’s syntax is
Elements can be any types — integer, strings, list, etc.
Now, let’s look at tuple specific property and then look it as a data records.
Tuples are immutable, meaning once a tuple is created elements on it cannot be added or removed. The order of elements is also fixed.
We also saw that tuple variable usa
‘s position has meaning — 0
for name of a country and 1
for name of a capital city.
Given these immutable property of tuple, it’s a perfect data structure to contain data — no side effect.
Let’s see an example:
Here you see tuples contain data about countries. We can extract tuple’s values using variables to contain them. We use *<variable-name>
for naming a variable to collect more than 1 values, for eg *rest
and *prev_info
in the code. This process is also know as tuple unpacking.
On running the file, we get:
north america: [('United States of America', 'Washington, D.C.', 'Bald Eagle'), ('Canada', 'Otaawa', 'Canada Jay')]country: Swaziland, capital: Mbabane, Lobamba, national bird: Purple-crested turacoUSA's national bird: Bald EagleGuyana's capital: Georgetownusa: United States of America, rest info: ['Washington, D.C.', 'Bald Eagle']
Now let’s look at namedtuple
factory function from Python's collections
libraries.
The namedtuple
combines class and tuple approach so that we can give meaningful names to the positions.
Let’s see an example:
Here we created a tuple called Rectangle
that has two fields — length
and breadth
. We can access the value of the Rectangle
tuple using index or through attribute. We can also unpack it using normal unpacking way.
We can get a dictionary representation of a tuple using _asdict()
. We can create a new instance of Rectangle
using values from existing instance. Here we used unpacking dictionary and unpacking positional argument way to do so.
On running the file, we get:
calculating area using indexing: 18calculating area using attribute: 18length: 9, breadth: 2dict representation: {'length': 9, 'breadth': 2}r2's initial id: 140454374705088r2's length: 9, breadth: 3r2's id after replacing breadth value: 140454374705280r3's lenght: 9, breadth: 2
What if we want to have default values for the fields in namedtuple
? We do have 2 ways to do it — prototype and using __defaults__
property of tuple.
First, let’s look at the prototype way:
On running the file, we get:
prototype circle's id: 140367016505888
area: 12.57, id: 140367016746416
Here while creating an instance of a Circle
called circle_zer
, we passed default values to the fields. Remember that once we started passing default values, it should do that to all the remaining fields that comes after it. This is to help disambiguate value assignment to variable for Python compiler. If you did not give default values, you’ll get positional argument
error.
So the instance with default values will became our prototype. We can create an instance based on the prototype using _replace
method. Since tuples are immutable sequence type, see that the prototype object and new instance out of prototype have different id.
Second way is using __defaults__
property.
Here we used __defaults__
attribute to pass default values to fields in Circle
tuple. The default values gets passed from left to right, so if we had just pass 2 values they would be set to origin_x
and origin_y
fields .
It would work similarly in function as well:
Now let’s look at a scenario where we want to extend our existing tuple, Circle
. We would like to add origin_z
field to the Circle so that this Circle works in 3D environment to become Sphere. We can do it by using _fields
attribute of tuple to get fields from 2D Circle
and add a new origin_z
field. Then follow usual namedtuple
way of setting and access values of the tuple.
Let’s see an example:
On running the file, we get:
circle area: 28.27 at coordinate (1, 1)
sphere area: 113.10 at coordinate (1, 1, 1)
In conclusion,
- tuples are an immutable data structure
- tuples can work as a data record
- we have
namedtuple
factory function to create tuple with named fields.
I hope the article was helpful and got to know tuples better.
Congratulations on the completion and thank you for reading! 💐 My next article will be on mutability and immutability of Python’s data structures. See you then.