I have a list of namedtuples named Books
and am trying to increase the price
field by 20% which does change the value of Books
. I trie
Named tuples are immutable, so you cannot manipulate them.
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.
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)