Tuples
Definition
- A tuple is an ordered sequence of any type of values and can be created as a set of comma separated values within parenthesis and indexed by integers.
- The difference between list and tuple is that tuples are immutable.
Syntax:
tuple=(element1, element2, element3)
Example:
tuple=(“Mari”,2017,9.5)
Tuple creation
- The tuple values are enclosed within parenthesis and separated with comma.
- The parenthesis is optional and we can create a tuple without them.
- To create a tuple with only one element, we have to include a comma at the end.
Syntax:
tuplename=()
tuplename=(element1, element2, element3)
tuplename=element1, element2, element3
tuplename=(1,)
Tuple accessing
Indexing and slicing can be used to access a tuple elements. The indices of tuple elements are numbered from 0 from left end and numbered from -1 from right end.
Example:
Tuple=(‘Mari’, 2017, 9.5)
Tuple[0]
Tuple[-1]
Tuple[0:1]
Output:
‘Mari’
9.5
‘Mari’
Tuple deletion
To delete a tuple and all the elements stored in it, use the keyword del.
Syntax
del tuplename
Example
tuple=(1,2,3,4,5)
del tuple
print(tuple)
Output
Error
Tuple updation
Tuple is immutable. We cannot alter its elements.
Example:
Tuple1=(1,2,3,4,5)
Tuple1[0]=6
Output:
Error
Tuple assignment
Python has a feature that is the ability to have a tuple on the left hand side of an assignment statement. This allows you to assign more than one variable at a time when the left hand side is a sequence.
Example
Tuple1=(‘good’,’morning’)
x,y=Tuple1
print(x)
print(y)
x,y=y,x
print(y)
a,b=1,2,3
Output
‘good’
‘morning’
‘good’
Error
Tuple as return value
Funtions can return tuples as return values. A function can only return one value but if the value is a tuple the effect is the same
Example1:
If you want to divide two integers and compute the quotient and remainder. It is better to compute them both at the same time. The built-in function divmod takes two arguments and returns a tuple of two values.
tuple1=divmod(7,3)
print(tuple1)
quotient,remainder=divmod(7,3)
print(quotient)
print(remainder)
Output
(2,1)
2
1

No comments:
Post a Comment