Introduction
In this project, you will learn how to implement a simple named tuple in Python. A named tuple is a data structure that allows you to access data using both positional indexing and attribute names, providing a more intuitive and readable way to work with structured data.
👀 Preview
## Output
🎯 Tasks
In this project, you will learn:
- How to create a
NamedTupleclass that inherits from the built-intupleclass - How to implement the
__init__,__new__,__getitem__, and__repr__methods to achieve the desired functionality - How to access data using both positional indexing and attribute names
- How to represent the
NamedTupleinstance in a readable format
🏆 Achievements
After completing this project, you will be able to:
- Understand the concept of named tuples and their benefits
- Implement a simple named tuple class in Python
- Use the named tuple to access and represent structured data in a more intuitive way
Implement the NamedTuple Class
In this step, you will learn how to implement the NamedTuple class, which allows you to access data using both positional indexing and attribute names.
- Open the
namedtuple.pyfile in your code editor. - Define the
NamedTupleclass, which should inherit from thetupleclass. - In the
__init__method, accept two parameters:iterable(the data) andfields(the names for the data). - Store the
iterableandfieldsas instance variablesself.dataandself.fields, respectively. - Use a
forloop to iterate over thefieldsand set each field as an attribute of theNamedTupleinstance, assigning the corresponding value fromself.data. - Implement the
__new__method to create a new instance of theNamedTupleclass. This method should call the__new__method of thetupleclass and return the new instance. - Implement the
__getitem__method to allow accessing the data using both positional indexing and attribute names. If the index is a string, find the index of the corresponding field inself.fieldsand return the value fromself.data. - Implement the
__repr__method to return a string representation of theNamedTupleinstance in the formatNamedTuple(x=1, y=2), wherexandyare the field names, and1and2are the corresponding values.
Your completed NamedTuple class should look like this:
class NamedTuple(tuple):
def __init__(self, iterable, fields):
self.data = iterable
self.fields = tuple(fields)
for i, attr in enumerate(self.fields):
setattr(self, attr, self.data[i])
def __new__(cls, iterable, fields):
return super().__new__(cls, iterable)
def __getitem__(self, index):
if isinstance(index, str):
index = self.fields.index(index)
return self.data[index]
def __repr__(self):
return f"NamedTuple({', '.join(f'{field}={self[field]}' for field in self.fields)})"
Test the NamedTuple Class
In this step, you will test the NamedTuple class you implemented in the previous step.
- In the
namedtuple.pyfile, add the following code at the end of the file:
if __name__ == "__main__":
## Example usage:
testData = [1, 2]
fields = ["x", "y"]
t = NamedTuple(testData, fields)
print(t) ## Output: NamedTuple(x=1, y=2)
print(t[1]) ## Output: 2
print(t.x) ## Output: 1
- Save the
namedtuple.pyfile. - Open a terminal or command prompt and navigate to the directory containing the
namedtuple.pyfile. - Run the following command to execute the script:
python3 namedtuple.py
You should see the following output:
NamedTuple(x=1, y=2)
2
1
This demonstrates that the NamedTuple class is working as expected, allowing you to access the data using both positional indexing and attribute names.
Congratulations! You have successfully implemented a simple named tuple in Python.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



