Python namedtuple
2022-12-30
TIL
>>> from collections import namedtuple
>>> nt = namedtuple('nt', ['value', 'id'])
>>> a = nt('item', '1')
>>> a
nt(value='item', id='1')
>>> a.value
'item'
>>> a.id
'1'
How I used (unnamed) tuple in my solution for Advent of Code challenge 2022/day/20
>>> items = ['๐', '๐']
>>> items_with_index = []
>>> for i, item in enumerate(items):
... items_with_index.append((item, i))
...
>>> items_with_index
[('๐', 0), ('๐', 1)]
>>> items_with_index[0][0]
'๐'
How it could've been done with namedtuple
>>> from collections import namedtuple
>>> nt = namedtuple('nt', ['item', 'id'])
>>> items = ['๐', '๐']
>>> items_with_index = []
>>> for i, item in enumerate(items):
... items_with_index.append(nt(item, i))
...
>>> items_with_index
[nt(item='๐', id=0), nt(item='๐', id=1)]
>>> items_with_index[0].item
'๐'