Named tuples are immutable, so you cannot manipulate them.
Right way of doing it:
If you want something mutable, you can use recordtype
.
from recordtype import recordtype
Book = recordtype('Book', 'author title genre year price instock')
books = [
Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20),
Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)]
for book in books:
book.price *= 1.1
print(book.price)
PS: You may need to pip install recordtype
if you don’t have it installed.
Bad way of doing it:
You may also keep using namedtuple
with using the _replace()
method.
from collections import namedtuple
Book = namedtuple('Book', 'author title genre year price instock')
books = [
Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20),
Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)]
for i in range(len(books)):
books[i] = books[i]._replace(price = books[i].price*1.1)
print(books[i].price)