Home > python > namedtuple


A namedtuple can be used as a simple class where you want to group together some attributes, you want to name them, and you don’t need any methods. As its name suggests, it’s a tuple, but you can assign names to the attribues.


from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])    # name of the "struct" and its attributes
# Point = namedtuple('Point', 'x y')       # it would also work, and it means the same
                                           # the 2nd parameter can be a single space-delimited string

def main():
    p = Point(x=1, y=4)
    print(p)                # Point(x=1, y=4)
    p = Point(1, 4)
    print(p)                # Point(x=1, y=4)
    print(p.x)              # 1
    print(p[0])             # 1
    print(p == (1, 4))      # True
Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: