DEV Community

Phondanai
Phondanai

Posted on

1

Bite-Size Python: Tuples and namedtuple

Tuple is one of the sequence data type like List in Python. The key main difference is tuple is immutable which mean once you create tuple you can not change it's value (but we can create new tuple from existing one after processing or something).

This post will demonstrate basic tuple operations and enhance it usage using namedtuple

Let's start

Creating tuple

# empty tuple can create using ()
>>> a_tuple = ()
# we can check that it is really a tuple
>>> type(a_tuple)
# <class 'tuple'>

# create tuple with data
>>> a_tuple = (1,) # one element tuple must include comma
>>> a_tuple
(1,)

# create tuple using `tuple` function with sequence data type like `list` 
>>> a_list = [1, 2, 3, 4, 5]
>>> a_tuple = tuple(a_list)
>>> a_tuple

Accessing data in tuple

# same manner of list by using zero-based indexing number
>>> a_tuple[0]
1

# slicing works as expect
>>> a_tuple[:3]
(1, 2, 3)

You can't modify tuple once it created

>>> a_tuple[0] = "others"
# will raise --> TypeError: 'tuple' object does not support item assignment

# but we can work around by create new one using existing values
>>> a_tuple = ("others",) + a_tuple[1:] # using `+` sign to join tuples
>>> a_tuple
('others', 2, 3, 4, 5)

You can't remove item from tuple using del too

>>> del a_tuple[-1]
# TypeError: 'tuple' object doesn't support item deletion

# `del` can only remove entire of the tuple
>>> del a_tuple

namedtuple is like an enhance version of tuple.
Key difference between these two guys is, innamedtuple you can naming something to tuples and you can accessing the value in namedtuple using name make it clearer and easy to read (but you can still use index number if you like.

# import first before using namedtuple
>>> from collections import namedtuple
# create namedtuple name `Point` consists of `x` and `y` 
# representing x, y coordinate system
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(20, -20) # x = 20, y = -20
>>> p.x
20
>>> p.y
-20

Useful functions in namedtuple

# return as a dictionary
>>> p._asdict()
{'x': 20, 'y': -20}

# replacing value
# this will return new namedtuple not in-place replacing
>>> p._replace(x=0, y=0)
Point(x=0, y=0)

Thanks for reading! :)

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay