Tuple:
v A tuple is same as list, except that the set
of elements is enclosed in parentheses instead of square brackets.
v A tuple is an immutable list. i.e. once a
tuple has been created, you can't add elements to a tuple or remove elements
from the tuple.
v But tuple can be converted into list and list
can be converted in to tuple.
v Tuples are faster than lists.
v If the user wants to protect the data from
accidental changes, tuple can be used.
v Tuples can be used as keys in dictionaries,
while lists can't.
1.
Indexing
2.
Slicing
3.
Concatenation
4.
Repetitions
5.
Membership
6.
Comparison
Tuple is
immutable so changes cannot be done on the elements of a tuple once it is
assigned.
v Tuple assignment allows, variables on the left
of an assignment operator and values of tuple on the right of the assignment
operator.
v Multiple assignment works by creating a tuple
of expressions from the right hand side, and a tuple of targets from the left,
and then matching each expression to a target.
v Because multiple assignments use tuples to
work, it is often termed tuple assignment.
v It is often useful to swap the values of two
variables.
a=20
b=50
temp = a
a = b
b = temp
print("value
after swapping is",a,b)
a=20
b=50
(a,b)=(b,a)
print("value
after swapping is",a,b)
Multiple values
can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
v A Tuple is a comma separated sequence of
items.
v It is created with or without ( ).
v A function can return one value. if you want
to return more than one value from a function. we can use tuple as return
value.
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
enter a value:4
enter b value:3
reminder: 1
quotient: 1
def min_max(a):
small=min(a)
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
smallest: 1
biggest: 6
The parameter
name that begins with * gathers argument into a tuple.
def
printall(*args):
print(args)
printall(2,3,'a')
(2, 3, 'a')
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.