[Python Tips] Named Tuples

What is a tuple?

Tuples are very similar to lists, but it is unable to be changed (immutable). This provides a tiny performance and memory savings. More importantly provides a hint to the interpreter and some code protection when you know a data structure shouldn't be changing.

The difference in performance is not something you should code for unless you are working with extremely large datasets. The fact they are immutable is the main reason to use tuples over a list.

The syntax of a tuple is almost exactly like a list, except you use ( ) instead of [ ].

List

['Bob Jones', 'Manager', 'Denver']

Tuple

('Bob Jones', 'Manager', 'Denver')

What is a named tuple

A named tuple is a module from the collection class that allows you to name the elements in a tuple so they can act as a lightweight class or enum.

Example Usage

from collections import namedtuple
Employee = namedtuple('Employee', ['name', 'role', 'location'])
bob = Employee('Bob Jones', 'Manager', 'Denver')
print(bob.name)

collections is a default package and you do not need to install it, but you will need to import it. Accessing the name of an Employee data set is really easy and readable. It makes for easier to read code and fewer bugs and is very lightweight. In some text editors/IDEs it can also provide code insight and auto-completion.

If you have objects that should not be changing and don't require methods (class functions) then tuples are likely are a better choice than a list.

My Python Tips Series

X48EJ

Why you should vote me as witness

Witness & Administrator of four full nodes

themarkymark.png

My recent popular posts

STEEM, STEEM Power, Vests, and Steem Dollars. wtf is this shit?
The truth and lies about 25% curation, why what you know is FAKE NEWS
WTF is a hardware wallet, and why should you have one?
GINABOT - The Secret to your Sanity on Steemit
How to calculate post rewards
Use SSH all the time? Time for a big boy SSH Client
How to change your recovery account
How curation rewards work and how to be a kick ass curator
Markdown 101 - How to make kick ass posts on Steemit
Work ON your business, not in your business! - How to succeed as a small business
You are not entitled to an audience, you need to earn it!
How to properly setup SSH Key Authentication - If you are logging into your server with root, you are doing it wrong!
Building a Portable Game Console

H2
H3
H4
3 columns
2 columns
1 column
15 Comments
Ecency