named tuple in python code example

Example 1: create a named tuple python

>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'first_name last_name zip_code')
>>> p1 = Person('Joe', 'Schmoe', '93002')
>>> p1.first_name
'Joe'
>>> p1[0]
'Joe'
>>> p1.zip_code
'92002'
>>> len(p1)
3
>>> type(p1)
<class '__main__.Person'>
>>>

Example 2: what is a tuple in python

# A tuple is a sequence of immutable Python objects. Tuples are
# sequences, just like lists. The differences between tuples
# and lists are, the tuples cannot be changed unlike lists and
# tuples use parentheses, whereas lists use square brackets.
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = "a", "b", "c", "d";

# To access values in tuple, use the square brackets for
# slicing along with the index or indices to obtain value
# available at that index.
tup1[0] # Output: 'physics'