Tuples in Python


Tuples are sequences which work just like lists the only difference is that they are immutable which means we can’t add, remove or modify it’s elements once it is created. This also makes them super efficient in comparison to list. Tuples are used to store a list of items which don’t change.

Creating Tuples

Tuples can be created by listing elements separated by a comma (,) inside a pair of parentheses i.e (). Here are some examples:

Here is how we can create an empty tuple:

We can also use constructor function i.e tuple(), which accepts any type of sequence or iterable object.

List comprehension can also be used to create tuples.

To create a tuple with just one element, you must type the trailing comma after the value, otherwise, it will not be a tuple. For example:

The use of parentheses to enclose the elements of a tuple is optional. It means we can also create tuples like this:

Notice that, although we didn’t use parentheses while creating tuples, Python uses them while printing tuples.

Just as before, to create a tuple with one element trailing comma (,) after the value is required.

We will use parentheses explicitly while creating tuples. However, the other form also has its uses, most notably while returning multiple values from a function.

Tuple Unpacking

Tuples let you assign values to multiple variables at once. For example:

This is known as Tuple Unpacking. The number of variables (on the left side) and the number of elements in the tuple (on the right side) must match otherwise you will get an error.

Since the parentheses are optional, the above code can also be written as:

Recall that we have already learned about this in Lesson Data Types and Variables In Python, under the title Simultaneous Assignment. Well, now you know behind the scenes we were using tuples unknowingly!

Operations on Tuples

A tuple is essentially an immutable list. As a result, most of the operations that can be performed on a list are also valid for tuples. Here are some examples of such operations:

  • Access a single element or slices of elements using [] operator.
  • built-in functions like max(), min(), sum() are valid on a tuple.
  • Membership operator in and not in.
  • Comparison operators to compare tuples.
  • + and * operators.
  • for loop to iterate through elements.

and so on.

Whenever you are facing a dilemma whether an operation is valid for a tuple or not, just try it out in the Python Shell.

The only type of operations which tuple doesn’t support are the ones that modify the list itself. Therefore methods such as append(), insert(), remove(), reverse() and sort() don’t work with tuples.

The following program demonstrates some common operations that can be performed on tuples.



Leave a Comment

%d bloggers like this: