Tuples
• Tuples areworks exactly like lists.
• Tuple is similar to lists since the value of the items
stored in the list can be changed whereas the tuple is
immutable and the value of the items stored in the tuple
can not be changed.
• There fore in Python “Tuple” is used to store the
sequence of immutable python objects.
3.
Creating tuple
• Atuple can be written as the collection of comma-
separated values enclosed with the small brackets.
tuple() function
• Analternative way of creating a tuple is by using
tuple() function.
• The tuple() function is a built-in function in
Python that can be used to create a tuple.
• Syntax :
tuple(iterable)
This function accepts a single parameter iterable
(optional). It is an iterable(list, range etc..) or an
iterator object.
Inbuilt functions fortuple
• count(x) : Returns the number of occurrences
of element x
14.
Indexing and slicing
•Tuples are like lists , so indexing and slicing of
tuple is similar to that of lists.
• The indexing operator “[ ]” is uses to access
elements of a tuple.
• The index must be an integer; so we cannot use
float or other types. This will result in “type error”.
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the
second last item and so on.
Operations on tuples
•Operators can be used to concatenate or
multiply tuples.
• Concatenation is done with the ”+” operator
• Multiplication is done with the ”*” operator.
Repetition operator
• “*”: The multiplication operator is used to
replicate the elements of the tuple.
19.
Passing variable lengtharguments to tuples
• The special syntax ”*args” in function definitions in
python is used to pass a variable number of arguments
to a function
• syntax to create a function that can take variable length
arguments.
def function_name(*args) :
#
# body of the function
#
• *args: holds variable length arguments.
Soring tuples
• Atuple does not contains any method named
sort.
• In order to sort a tuple, first convert a tuple in
to a list, after conversion use sort() method for
lists and again convert it into a tuple.
Traverse tuples froma list
• A tuple assignment can be used in the for loop
to traverse a list of tuple.
27.
zip() function inpython
• The zip() is an inbuilt function in python.
• The zip() function takes items in a sequence
from a number of collections(list, tuple, set ,
etc …) and aggregates them in a tuple, and
return it.