Tuples - Python (2016)

Python (2016)

CHAPTER 10: Tuples

Towards the end of the previous chapter, we learned that there is a Python data type that can be much faster than lists, though not quite as flexible. These are tuples, which are immutable sequences. In nature, lists and tuples are very similar—except that you will not be able to dynamically modify the tuple in the same way that you do lists.

Once a tuple is created, it can no longer be modified or changed. The way that this affects how the tuple is stored in the memory will be an important idea later on. In order to create a tuple, the programmer will create a group of items that are separated by a comma (,). While Python adds parentheses around any item group, it will not be as important, since the result will still be a tuple. This is demonstrated below:

>>>spam=1,2,3

>>>spam

(1,2,3)

>>>”Q”,”W”,”E”,”R”

>>>(‘Q,’W’,’E’,’R’)

Now, here is a little riddle: what if you only want one item to be stored in your tuple? This can simply be done by leaving an extra comma at the end. In fact, you can choose to leave an excess comma after any tuple, regardless of its size (even though this is not explicitly required for any tuple larger than one). This is one of those little quirks unique to the Python language.

Note as well that you can make an empty tuple simply through an empty pair of parentheses.

Indexing Tuples

Just like lists and strings, tuples follow the standard indexing rules. Staring from the left, indexing begins counting from 0; from the end, it counts from -1. Extend slicing is also supported. You can review this from the previous chapter, since this can be quite tricky.

Built-in Functions

Like in lists, there are also some built-in functions for tuples. There are only two of them, though, owing to the relative inflexibility of tuples.

.count() - This returns the number of times that a specific item is found. It also works in the same way as .count() for lists.

.index() - This locates the first index of the specified item. It also works like .index() for lists.

Using Tuples

Just like lists, tuples were made for a specific type of usage. They are perfect for holding data you want to be static, and that you don’t plan or changing or modifying. Just like what is said in the previous lesson, a tuple is up to seven times faster than lists. This means that for each item in a list that is manipulated, four to seven tuples could have been manipulated in the same time frame. This generates a huge advantage in speed, especially for scientific work.

Though this sounds very good, remember that once a tuple is created it can no longer be changed. The best metaphor for this is that tuples are “read-only”. In order to change the content, tuples have to be changed into dynamic an mutable sequences. Only after manipulation are they converted back into tuples. For this same reason, those intending to add and remove items in sequences should not use tuples.