Python Data StructureEnhance your tuples

time to read 1 min | 110 words

Standard Python tuples are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios.

Instead, the collections module provides an enhanced version of a tuple, namedtuple, that makes member access more natural (rather than using integer indexes).

Import namedtuple:

from collections import namedtuple

Create a namedtuple object:

point = namedtuple('3DPoint', 'x y z')
A = point(x=3, y=5, z=6)
print(A)
# 3DPoint(x=3, y=5, z=6)

Access a specific member:

print(A.x)
# 3

Because namedtuples are backwards compatible with normal tuples, member access can be also done with indexes:

print(A[0])
# 3

To convert a namedtuple to a dict (Actually an OrderedDict):

print(A._asdict())
#OrderedDict([('x', 3), ('y', 5), ('z', 6)])


This is a post in the Python Data Structure series.
Other posts in this series:

  1. May 03, 2017 Enhance your tuples
  2. May 02, 2017 Get more with collections!
  3. Dec 26, 2016 Queue in Python - Part 3
  4. Nov 02, 2016 Queue in Python - Part 2
  5. Nov 02, 2016 Queue in Python - Part 1

Related Post:

  1. May 25, 2017 New interesting data structures in Python 3
  2. May 22, 2017 Keyword argument demystify
  3. May 04, 2017 Looping techniques in Python
  4. May 02, 2017 Get more with collections!
  5. May 01, 2017 There is more to copying
  6. Apr 30, 2017 Implementing weak references in Python
  7. Apr 26, 2017 Next, Function or Method ?
  8. Apr 24, 2017 Generator Expressions
  9. Apr 23, 2017 Yield Keyword
  10. Apr 21, 2017 What are Generators?
  11. Apr 16, 2017 Lambda Functions in Python
  12. Apr 06, 2017 Function in Python are First-Class Object
  13. Apr 05, 2017 Django 1.11 Release Note a Reading
  14. Apr 03, 2017 One Hell Named JSON
  15. Dec 26, 2016 Queue in Python - Part 3
  16. Nov 02, 2016 Queue in Python - Part 2
  17. Nov 02, 2016 Queue in Python - Part 1
  18. Jun 25, 2016 Enable Spark Context on Your Ipython Notebook
  19. Apr 27, 2015 EAFP Coding Style in Python
  20. Jul 24, 2014 Kompresi CSS menggunakan Python