Tuples in Python.pptx
Tuples in Python.pptx
A tuple is an ordered sequence of elements of different data types such as integer, float, string, list
or even a tuple.
Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas.
Like list and string, elements of a tuple can be accessed using index values starting from 0.
If there is only a single element in a tuple then the element should be followed by comma.
If we assign the value without comma it is treated as integer.
Sequence without parenthesis is treated as tuple by default.
Accessing elements in a Tuple
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
Tuple is Immutable
Tuple is immutable data type. It means that the elements of a tuple cannot be changed
after it has been created. An attempt to do this would lead to an error.
Tuple Operations
Concatenation
Python allows us to join tuples using concatenation operator +
We can also create a new tuple which contains the result of this concatenation.
Tuple Operations
Concatenation
Concatenation operator can also be used for extending an existing tuple. When we extend a
tuple using concatenation a new tuple is created.
Tuple Operations
Repetition
Repetition operation is depicted by symbol *. It is used to repeat elements of a tuple. We can
repeat the tuple elements . The repetition operator requires the first operand to be a tuple and
the second operand to be an integer only.
Tuple Operations
Membership
The in operator checks if the element is present in the tuple and returns True, else it returns False.
Tuple Operations
Slicing
Like string and list, slicing can be applied to tuples also.
Program to create a nested tuple to store roll number, name and marks of students
\t is an escape
Output character used for
adding horizontal
tab space. Another
commonly used
escape character is
\n, used for inserting
a new line.
Program to swap two numbers without using a temporary variable.
Program to compute the area and circumference of a circle using a function.
Write a program to input n numbers from the user. Store these numbers in a tuple. Print
the maximum and minimum number from this tuple.