top of page

Python: Working with tuple

  • tuple

  • How to create tuple

  • How to access elements of tuple

  • Mathematical operation

  • Important functions of tuple

  • tuple packing and tuple unpacking

  • tuple comprehension

  • Differences between list and tuple

tuple:

tuple is similar to list except that it is immutable. once you create tuple object you can not perform any modification in the existing object.

How to create tuple:

Empty tuple: t=()

Empty tuple: t=()

tuple with single value: t=(10,)

tuple with single value: t=(10,)

Single valued tuple should end with comma. if comma is not put, it will be treated as int value .

Single valued tuple should end with comma. if comma is not put, it will be treated as int value .

tuple with multiple value: t=(10,20,30)

tuple with multiple value: t=(10,20,30)

Use of brackets () is optional here, as evident from below example:

Use of brackets () is optional here, as evident from below example:

tuple with a sequence: t = tuple(sequence)

tuple with a sequence: t = tuple(sequence)

How to access elements of tuple:

1. by using Index:

using Index: Python

2. by using slice operator:

slice operator: Python

Mathematical operation:

+ is used to concatenate two tuples

Mathematical operator: Python

* repetition operator

Mathematical operator: Python

Important functions of tuple:

1. len():  it is used to find number of characters in a tuple.

Example

Important functions of tuple: Python

2. count(): used to count number of times a character is present in a tuple.

Example

Important functions of tuple: Python

3. index(): used to find index of element in a tuple. if the specified  element is not available we will get value error.

Example

Important functions of tuple: Python

4. sorted(): to sort elements based on natural sorting order. sort() is not available in tuple because tuple is immutable.

Example

Important functions of tuple: Pythong

5. min() and max(): It is only for homogeneous object not for heterogeneous.

Example

Important functions of tuple: Python

6. cmp()

cmp is  available in python 2 only not in python 3

cmp(t1,t2)

  • If t1 is equal to t2, then it returns 0

  • If t1 is smaller than t2, then it returns -1

  • If t1 is greater than t2, then it return +1

tuple packing and tuple unpacking:

Packing: grouping into single.

tuple packing and tuple unpacking: Python
tuple packing and tuple unpacking: Python

Unpacking:

tuple packing and tuple unpacking: Python
tuple packing and tuple unpacking: Python

tuple comprehension:

Tuple comprehension is supported but result is not tuple but  some generator object.

tuple comprehension: Python
tuple comprehension: Python

#Write a program to take a tuple of numbers from the keyboard and print sum, avg.

#Write a program to take a tuple of numbers from the keyboard and print sum, avg.

Differences between list and tuple:

Differences between list and tuple:
bottom of page