Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python namedtuple

import collections

# create a named tuple called Person with fields of first_name, last_name, and age
Person = collections.namedtuple('Person', ('first_name', 'last_name', 'age'))

# Note a named tuple can have fields names as string using a space as a delimiter also see example below
Person = collections.namedtuple('Person', 'first_name last_name age')

# initialize a user as a Person Tuple
user = Person(first_name="John", last_name="Doe", age=21)

# print user named tuple
print(user)

# print user by field names
print(user.first_name, user.last_name, user.age)

# print length of user
print(len(user))

# print first name by index
print(user[0])

# loop through user
for item in user:
   print(item)

Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #namedtuple
ADD COMMENT
Topic
Name
1+5 =