The named tuples in Python are tuples which can be accessed using named fields and named attributes.
It is always better to make use of the named tuples in your Python code as it improves readability.
We can import namedtuple function from collections module which lets us create named tuples.
from collections import namedtuple MyTuple = namedtuple('MyTuple', ['field1', 'field2', ...])
Let's take a look at a few examples.
from collections import namedtuple # A named tuple called 'City' with fields 'name', 'country', and 'population' City = namedtuple('City', ['name', 'country', 'population']) london = City('London', 'United Kingdom', 8908081) new_york = City('New York', 'USA', 8537673) tokyo = City('Tokyo', 'Japan', 13929286) print(london.name, london.country, london.population) print(new_york.name, new_york.country, new_york.population) print(tokyo.name, tokyo.country, tokyo.population)
London United Kingdom 8908081 New York USA 8537673 Tokyo Japan 13929286
As you may see, we created a named tuple with named field - City and named attributes - 'name', 'country', and 'population'
We were able to access the files using dot notation.
Let' take a look at another example.
from collections import namedtuple PlotData = namedtuple('PlotDataXY', ['x', 'y']) plot = PlotData(2, 5) print(plot.x) print(plot.y)
Read More from The Offical Python Documentation:
Facing issues? Have Questions? Post them here! I am happy to answer!
- How to convert int to ASCII in Python
- How to make use of SQLite Module in Python?
- Split a String into Sub-string and Parse in Python
- Python: Pandas Rename Columns with List Example
- How to run Python file from Mac Terminal
- How to Exit a Loop in Python Code
- Python: How to Plot a Histogram using Matplotlib and data as list
- MD5 Hashing in Python
- Jupyter: Safari Cant Connect to the Server localhost:8888/tree
- Fix: AttributeError: str object has no attribute decode. Did you mean: encode?[Python]
- How to Read a binary File with Python
- How to add two float numbers in Python
- Python: How to install YAML Package
- Python: How to Save Image from URL
- What is Markdown in Jupyter Notebook with Examples
- How to change the Python Default version
- 33: Python Program to send an email vid GMail
- How to comment code in Python
- How to Fix AttributeError in Python
- Fix: error: Jupyter command `jupyter-nbconvert` not found [VSCode]
- How to comment out a block of code in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- Import Other Python Files Examples
- Python: How to add Progress Bar in Console with Examples
- 3 Ways to convert bytes to String in Python
- Github: How to Invite Collaborators - Git
- How to save a file as csv in Windows Notepad? - Microsoft
- Change color of macOS terminal prompt - MacOS
- How to install Terraform on M1/M2 Mac - MacOS
- Fix - sudo: systemctl: command not found - Ubuntu
- Bootstrap tooltip not working - Bootstrap
- How to make text bold using CSS - CSS