Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python named tuple

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)

Comment

python named tuples

from collections import namedtuple
A = namedtuple('A', 'a b c')
a = A(1,2,3)
a.b == a[1] # == 2
a == A(1,2,3) # is True
a[2] = 5 # TypeError: 'A' object does not support item assignment
len(a) # == 3
type(a) # <class '__main__.A'>
Comment

Basic example of a Named Tuple

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
Comment

PREVIOUS NEXT
Code Example
Python :: how to get the location of the cursor screen in python 
Python :: program to find even numbers in python 
Python :: opencv histogram equalization 
Python :: how to average in python with loop 
Python :: install log21 python 
Python :: polarean share price 
Python :: error warning tkinter 
Python :: how to change web browser in python 
Python :: filter for a set of values pandas dataframe 
Python :: convert number to binary python 
Python :: python list rotation 
Python :: np range data 
Python :: object.image.url email template django 
Python :: Writing Bytes to a File in python 
Python :: one hot encoding python pandas 
Python :: show all rows with nan for a column value pandas 
Python :: python every other including first 
Python :: pygame draw rect syntax 
Python :: from time import sleep, time 
Python :: pyqt5 change table widget column width 
Python :: prime number generator python 
Python :: python wait until 
Python :: python how to copy a 2d array leaving out last column 
Python :: how to take second largest value in pandas 
Python :: remove after and before space python 
Python :: pandas casting into integer 
Python :: import pyttsx3 
Python :: tkinter remove frame 
Python :: how to multiply two tuples in python 
Python :: how to join a list of characters in python 
ADD CONTENT
Topic
Content
Source link
Name
9+8 =