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 :: pandas python3 only 
Python :: operator overloading python 
Python :: flask flash The browser (or proxy) sent a request that this server could not understand. 
Python :: python global variable unboundlocalerror 
Python :: Implement a binary search of a sorted array of integers Using pseudo-code. 
Python :: i++ in python 
Python :: picture plot 
Python :: string slice python 
Python :: python print int operations 
Python :: strip plot 
Python :: how to create a new dataframe in python 
Python :: pandas filter columns with IN 
Python :: django password hashing 
Python :: include app in django project 
Python :: how to become python developer 
Python :: Removing Elements from Python Dictionary Using pop() method 
Python :: check for null values in rows pyspark 
Python :: .corr python 
Python :: iterate through dict with condition 
Python :: flow of control in python 
Python :: converting timezones 
Python :: read user input python 
Python :: how to get list size python 
Python :: local variable referenced before assignment 
Python :: stop for loop python 
Python :: run only few test cases in pytest 
Python :: python 2d matrix declare 
Python :: how to check if two strings are same in python 
Python :: prompt python 
Python :: add new element to python dictionary 
ADD CONTENT
Topic
Content
Source link
Name
2+9 =