In this article we will discuss what is tuple, how its different from list, different ways to create a tuple and iterate over it.

What is a tuple ?

Tuple is a kind of heterogeneous sequential container that can store elements of different types. Tuples are immutable i.e once created then we can not change it’s contents.
A sample tuple is as follows,

Unlike list, elements in tuple are wrapped using braces i.e. ‘(‘ & ‘)’

Difference between list and tuple

  • List is mutable i.e once created then we can modify its contents. Whereas, a Tuple is immutable i.e. once created we can change its contents, therefore tuple doesn’t provide functions like append(), remove() etc.
  • As tuple is immutable, so we can use it as key in a dictionary too.

Different ways to create a tuple

Create a tuple of different type of elements

We can create a tuple of different type of elements by just separating them with ‘,’ and wrapping them using braces i.e.

Output:

Create a tuple from unpacked elements

We can also create a tuple from unpacked elements i.e without any braces just elements separated by comma i.e.

Output:

Create an empty tuple

We can also create an empty tuple object like this,

Create a tuple from a list

We can also convert a list or any other sequential container to tuple by just type casting.
Suppose we have a list of int,

Let’s create a tuple from this list,

Output:

Iterate over a tuple

We can iterate over a tuple using for loop and in operator just like any other container in python i.e.

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.