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=()
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 .
tuple with multiple value: t=(10,20,30)
Use of brackets () is optional here, as evident from below example:
tuple with a sequence: t = tuple(sequence)
How to access elements of tuple:
1. by using Index:
2. by using slice operator:
Mathematical operation:
+ is used to concatenate two tuples
* repetition operator
Important functions of tuple:
1. len(): it is used to find number of characters in a tuple.
â€‹
Example
2. count(): used to count number of times a character is present in a tuple.
â€‹
Example
3. index(): used to find index of element in a tuple. if the specified element is not available we will get value error.
â€‹
Example
4. sorted(): to sort elements based on natural sorting order. sort() is not available in tuple because tuple is immutable.
â€‹
Example
5. min() and max(): It is only for homogeneous object not for heterogeneous.
â€‹
Example
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.
Unpacking:
tuple comprehension:
Tuple comprehension is supported but result is not tuple but some generator object.
#Write a program to take a tuple of numbers from the keyboard and print sum, avg.
Differences between list and tuple: