L

learnasyoulike

time


Python Tuples


Table of contents:


Python Tuples


Python tuples are very similar to lists. But unlike them, tuples are immutable objects and consume less memory in comparison to lists.

It is recommended to go through the details of python lists before reading about tuples.


Table of contents:


What are python tuples

A python tuple is an ordered collection of objects separated by commas. Or simply, it is a sequence of values.
(1, 2, 3) is a valid python tuple literal. Let us display it in IDLE shell:



We can assign a tuple (-5, 7, 3.8) to a variable.

Now t1 is a 'tuple' type variable. It is recommended to use parentheses while assigning a tuple, though this is not mandatory.

Now t2 is also a 'tuple' type variable.

Another example is given above.

Empty tuples

A tuple can hold any number of items, or no items at all. We can create an empty tuple as in the following.


We can also create an empty tuple by calling the python tuple() function.


However, once an empty tuple is created, we cannot add items to it, because tuples are immutable.

Properties of a Tuple

Tuples are ordered

Tuples are ordered. The tuple (4, 5, 6) and (5, 4, 6) are not the same. We can use the comparison operator == to check this



Tuples allow duplicate items

An item can be present multiple times in a tuple. This is opposite to python sets where all items are unique.


In the above, position 0, 2 and 4 have the same values -37, still they are distinct elements of the tuple.


Tuples are heterogeneous

A tuple can contain items or elements that are of different data-types.


The above tuple contains a 'float', a 'str' and an 'int' type object.


Tuples are immutable

A tuple is an immutable object. We cannot add, remove, insert or sort items of a tuple, as we can do with a list. This is why slice assignment is not allowed with tuples.



Tuples are faster

Tuples are faster in comparison to the other data-structures like lists. Tuples consume less memory due to the immutable property of them.

Singletone tuples

To define a tuple with a single item, it is not sufficient to enclose a single value in parentheses.


Type of variable a is not 'tuple', but 'int'. Here the (55) is treated as a simple expression which is evaluated to 55.

So, to assign a tuple with a single element, we put a comma after the value:

Both with and without parentheses work, but the comma is mandatory here.

Create tuple from iterables

The tuple() function can be used to generate a tuple from iterables like 'str', 'list' etc.

In the above, two tuples are created from a string object "java", and a list object [99, 88, 77, 66].


Two tuples are created from a set object and a dictionary object.

Length of a tuple: len() function

Python len() function is used to find the length of an object. When the argument is a tuple object, len(tuple) simply returns the length of the given tuple. In other words, the number of items in the tuple is returned.

An empty tuple has a zero length. Note that the data-type of variable length is 'int'.

Tuple indexing

Consider the tuple assigned to variable x:
x = (2.7182, "javascript", 97)

Normally, we require three separate variables to hold three python objects. But, in the above, a single tuple variable x points to three objects 2.7182, "javascript" and 97. The objects it points to are called items or elements of the tuple.

A python tuple of three items x = type 'tuple' length = 3 2.7182 javascript 97 x[0] x[1] x[2] item 'float' 'str' 'int' 0 1 2 index

Access an item by index

Every item of a tuple has an index depending on the position of the item. An index is an integer inside a pair of square brackets that is placed immediately after the tuple variable/object.

An index of zero refers to the first item of a tuple. The last item can be accessed with the index len(x) - 1

An item of a tuple can be accessed by the index of that item.


x[0] points to the 1st item 2.7182,
x[1] points to the 2nd item "javascript",
x[2] points to the 3rd item 97.
Calling x[3] will raise an IndexError because there is no 4rth item.



We can see that variable x is of type 'tuple'. But types of x[0], x[1] and x[2] are 'float', 'str' and 'int' respectively.
They are also independent variables, and can take part in any calculations.




Negative indexing

Like lists, tuples also support negative indexing. The first item can be accessed with the index -len(x). The last item of a tuple has an index -1.




x = 2.7182 javascript 97 0 1 2 -3 -2 -1

All of the following equality comparisons and identity comparisons return True:

Tuple slicing

Slicing tuples works in the same way as list slicing does. By slicing a tuple a range of items can be accessed.

Consider the tuple
z = (33, "javascript", 901, 5.6, -7, "c++", True).

Here, len(z), i.e., number of items is 7.

Applying a slice [1:6] on this tuple, we get an output of ('javascript', 901, 5.6, -7, 'c++')


Python starts at index 1 (item 'javascript'), and goes on including items, stops before index 6 (item 'c++'). The item at index 6 is not included.

The slice notation [5:] translates to "begin with item at index 5 and include rest of the list".


Like list slicing, the slice notation [::-1] reverses the order of items of a tuple.




With the slice notation [-1:-6:-2], negative step forces count backwards. Counting starts from the last item, stops before index -6, and every alternate items are included.




Note: The slice notation [:] can copy a tuple as done in case of lists.




Tuples being immutable, no slice assignment is allowed with the items of a tuple.

Tuples with slice() function

Similar to list, we can create a slice object and use with tuples.

Once this slice object last_three is ready in our hand, we can apply it to any tuple.

You can take a look in here to study how slice() function works.

Nested tuples

A python tuple can contain another tuple. Consider the following codes:


In the above, the tuple ("pi", 3.1415) itself is an element of another tuple t. Its index is 2. When we access t[2], we get the inner tuple as ouput.


t = 100 200 ("pi", 3.1415) 300 0 1 2 3 -4 -3 -2 -1

Note that the inner tuple ('pi', 3.1415) is a single unit/item. If we check len(t), length will be 4, not 5.
Also if we reverse tuple t, items inside the inner tuple remain in the same order.


Since t[2] refers to the inner tuple ("pi", 3.1415),
t[2][0] refers to the first item of it, and t[2][1] refers to the second one.


Nested Tuple 100 200 pi 3.1415 300 t[0] t[1] t[2] t[3] t[2][0] t[2][1]

Tuple Methods

Since python tuples are immutable, unlike lists, they do not support methods like .append(), .insert() etc.


Method .count() - Count number of occurance of an item

The .count(item) method counts the number of occurance of the given item in a sequence. In the above tuple, 35 is found four times; so output is 4.
The number 100 is not found in the tuple, so output is 0.


Method .index() - Find the index of an item

.index(item) method returns the index of the given item in a sequence. If item is present more than once, index of the first item is returned. In the above, only the index of first occurrence of 33 is returned.
If the given item is not found in the tuple, a ValueError is raised by the interpreter.

Membership with tuple

Python membership operators in and not in can be used to check whether an item is a member of a tuple or not.


Since the item "red" is a member of the tuple colours, the membership expression "red" in colours returns True. "pink" is not a member of the tuple, so the expression "pink" not in colours returns True.

Unpacking a tuple

In python, the tuple unpacking feature enables us to assign a single tuple to multiple variables.

We have to remember that the number of variables in the left side must match the number of items in the assigned tuple.

Python provides special unpacking with the * (asterisk) and _ (underscore) operators which will be discussed in a separate article.

Tuple concatenation

The concatenation operator + can join two tuples producing a new tuple.

The new tuple joined contains all the elements of p and q.



Tuple repetition

The repetition operator * repeats the items of a tuple.

The new tuple repeated now contains the elements of letters in repeated form.



    # Summary

  • 01 Python tuples are ordered collection of items.
  • 02 Tuples are immmutable objects, they are unmodifiable.
  • 03 Tuple index is zero-based.
  • 04 Every item has its own position(index).
  • 05 A tuple item is accessible by its index.



--- x ---









Want to leave a message for me?