Tuples in Python with Examples

Arvind Jena
3 min readFeb 12, 2022

--

Python Tuple

Tuple is a collection of homogeneous and heterogeneous values enclosed in parenthesis (). The items of tuple are separated with a comma (,).

Syntax: tuple= (‘item1’, ‘item2’, ‘item3’,’item4’)

A tuple is similar to a list. The difference between the two is that, tuple is an immutable data type i.e we cannot change the elements of a tuple once it is assigned, whereas list is a mutable data type. Tuples use round brackets, whereas lists use square brackets.

Example:

If we pass nothing in the round bracket, the tuple is empty.

Important Note: Creating a tuple with single element.

Having one element with parenthesis is not enough. We need a trailing comma to indicate that it is, a tuple, even if there is no second element.

Example:

Note: In the above example, we missed the trailing comma, so it is considered as a string.

Tuple Operations

1. Concatenation

Concatenation is the operation of combining two or more tuples. We use (+) operator to combine two tuples.

Syntax: t1= (‘item1’,’item2’)

t2= (‘item1’,’item2’)

t= t1 + t2

Example:

2. Replication

We can repeat the elements in a tuple for a given number of times using (*) operator.

Example:

3. Indexing

Indexing allows us to access individual elements in a tuple by using a numeric value.

Note: The index must be an integer, we cannot use float or any other type.

4. Slicing

We can access a range of item in a tuple.

Syntax: [start : end : step]

Note:

o Start is inclusive.

o End is exclusive.

o Step is increment between each index for slicing. (Optional)

Example:

Tuple Methods

Only two methods are available in tuple.

· Index() : searches the tuple for a specified value and returns the position.

Example:

· Count() : returns the number of occurance of a specified value.

Example:

Conclusion

In this article, we learned about python tuples. More specifically, what are tuples, difference between tuple and list, how to create tuple and available methods.

--

--