Chapter : Tuple
lEnclosed with in parentheses. ()
lTuple is a immutable
lIts link list
lThey can be heterogeneous (Need not to be same data type)
Syntax
<Tuple_name/variable_name> =(val1,val2,val3,….valn)
For example:
t1=(‘Apple’,’Mango’,’Orange’)
t1=(10,20,30)
Empty Tuple:
t1=()
Heterogeneous Tuple:
t1=(‘Apple’,100,23.25,’Python’)
Nested Tuple:
t1=((1,2,3),(10,20,30,40,50))
List within Tuple:
t1=([1,2,3],[4,5,6])
Tuple and list inside a tuple - a nested tuple
t1=((0,1,2,3),[‘a’,’b’,’python’])
Parentheses are not must
t1=10,20,30
CTM: list is Mutable but tuple is immutable
So,iterating through a tuple is faster as compared to list.
If we have data that is not required to be changed,then sorting this data in a tuple will ensure that it is not changed accidentally.
CTM:Tuple are immutable,but member objects may be mutable.
Tuple creation:
For example:
>>> t1=(10,20)
>>> t1
(10, 20)
Empty Tuple
>>> t1=()
>>> t1
()
>>> t1=10,20,30
>>> t1
(10, 20, 30)
>>> t1=('a',10,'python',[10,20,30],(1,2,3))
>>> t1
('a', 10, 'python', [10, 20, 30], (1, 2, 3))
>>> t1=(10,)
>>> t1
(10,)
>>> t1=((1,2,3),(10,20))
>>> t1
((1, 2, 3), (10, 20))
>>>
CTM: Indexing of tuple is just like indexing of list
1. Creating tuple with a single elements
>>>t1=(‘a’,)
2. Creating tuple using built-in function tuple()
>>> t1=tuple()
>>> t1
()
>>>
>>> t1=tuple(("python","programming"))
>>> t1
('python', 'programming')
>>>
Nesting of Tuples:
Tuple can be placed inside other tuple.
Accessing and Traversing a tuple :
A tuple is a sequence of values which can be of any type and they are indexed by integer.
Like lists there could be a positive indexing like 0,1,2., or negative indexing like -1,-2,-3.,
Positive Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
tuple | 1 | 20 | “a” | 100 | “python” | [10,20,”c”] | 20.25 |
Negative Index | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
>>> t1=(120,34,56,73,"python")
>>> t1[0]
120
>>> t1[-1]
'python'
>>> t1[-4]
34
>>> t1[4]
'python'
>>> t1[7]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
t1[7]
IndexError: tuple index out of range
>>>
Traversing a Tuple:
1. Using in operator using for loop
a=(1,2,3)
for i in a:
print(i)
Output
1
2
3
>>>
2. Using range() function
For example
a=(1,2,3)
l=len(a)
for i in range(l):
print(a[i])
>>>
1
2
3
Common Tuple Operation
1. Tuple Slicing
2. Tuple Addition /Concatenation
3. Tuple Multiplication/ Repetition
4. ‘in’ and ‘not in’ membership operator(in tuple)
5. index
Tuple Slicing
Slicing is used to retrieve a subset of values. A slice of a tuple is basically its sub tuple.
Syntax:
Tuple_name[start:stop:step]
Start : starting point
Stop : stopping point which is excluded
Step :step the size
For example:
t1=(1,2,3,4,5)
>>> t1=(1,2,3,4,5)
>>> t1[1:3]
(2, 3)
>>> t1[0:4]
(1, 2, 3, 4)
>>> t1[3:]
(4, 5)
>>> t1[:4]
(1, 2, 3, 4)
>>> t1[:4:-1]
()
>>> t1[::-1]
(5, 4, 3, 2, 1)
>>> t1[2::-1]
(3, 2, 1)
>>> t1[2::-2]
(3, 1)
>>> t1[2:5:-2]
()
>>>
3. Tuple Addition /Concatenation
Python allows you to join/concatenate two tuple. new elements can be added to a tuple using ‘+’ operator.
For example:
>>> x=10+20
>>> x
30
>>> x=(1,2,3)
>>> y=(10,20,30)
>>> x+y
(1, 2, 3, 10, 20, 30)
>>> z=x+y
>>> z
(1, 2, 3, 10, 20, 30)
>>> z[1:5]+x
(2, 3, 10, 20, 1, 2, 3)
>>> z[1:5]+x[0]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
z[1:5]+x[0]
TypeError: can only concatenate tuple (not "int") to tuple
>>> z[0:3]+x[1]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
z[0:3]+x[1]
TypeError: can only concatenate tuple (not "int") to tuple
>>> z[0:3]+y
(1, 2, 3, 10, 20, 30)
>>> z[0:3]+x[1]
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
z[0:3]+x[1]
TypeError: can only concatenate tuple (not "int") to tuple
>>> z[0:3]+x[1:2]
(1, 2, 3, 2)
CTM: We can only add tuple to tuple
Tuple Multiplication/ Repetition:
The multiplication operator(*) is used for repetition of the tuple.
For example:
>>> t1=(1,2,3)
>>> t1
(1, 2, 3)
>>> t1*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> (10,20)*4
(10, 20, 10, 20, 10, 20, 10, 20)
>>> t1[0:2]*2
(1, 2, 1, 2)
>>>
>>> t1*'hi'
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
t1*'hi'
TypeError: can't multiply sequence by non-int of type 'str'
>>>
CTM: *operator requires a tuple and an integer as operators
‘in’ and ‘not in’ membership operator(in tuple)
The ‘in’ operator check whether a give element is contained in a tuple. It returns true if element is present in the tuples otherwise returns false.
For example:
>>> 4 in (1,2,3,4,56)
True
>>> 40 in (1,2,3,4,56)
False
>>>
>>> t1=(1,2,3,4,5,6)
>>> 2 in t1
True
>>> 20 in t1
False
>>> 2 in t1[0:3]
True
>>>
‘not in’ operator returns true if elements does not appear in the tuples,otherwise returns true
For example:
>>> t1=(1,2,3,4,5)
>>> 21 not in t1
True
>>> 2 not in t1
False
>>> 2 in(10,20,34)
False
>>> 20 in(10,20,34)
True
>>> 2 not in t1[0:2]
False
>>>
Index
Syntax:
Tuple.index(elem)
For example:
>>> t1.index(2)
1
>>> t1.index(5)
4
>>>
Comparing Tuple
Comparing tuple operator <,>,==,!= etc.,
For example
>>> (1,2,3)>(0,1,2)
True
>>> (0,1,20000)<(0,3,4)
True
Deleting a Tuple:
The del statement is used to delete a tuple.
For example:
>>> t1=(1,2,3)
>>> t1
(1, 2, 3)
>>> del t1
>>> t1
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
t1
NameError: name 't1' is not defined
>>>
False
>>>
Function in tuple:
1. Len()
Return the length of types
Syntax:
len(<tuple>)
example
P=(1, 45.25, 'hi', (10+8j), [10, 20, 30, 40], 'hello', (100, 200), 10)
>>>len(p)
8
2. max()
Maximum number
Syntax
Max(<tuple>)
u=(1,20,3,7,4,7)
max(u)
20
l=("one","two","a","B")
max(l)
'two'
3. Min()
Minimum number
Syntax
min(<tuple>)
u=(1,20,3,7,4,7)
min(u)
1
l=("one","two","a","B")
min(l)
'B'
4. sum()
Return sum of values
Syntax
Sum(<tuple>)
Example:
u=(1, 20, 3, 7, 4, 7)
sum(u)
42
5. index()
It return the index of existing elements in a tuples
Syntax:
<variable_name>=Index(<item>)
u=(1, 20, 3, 7, 4, 7)
u.index(20)
1
6. count()
Number occurrences in a elements
Syntax:
u=(1, 20, 3, 7, 4, 7)
u.count(7)
2
u.count(4)
1
u.count(40)
0
7. Sorted()
Syntax:
Sorted(<tuple>)
sorted(u)
[1, 3, 4, 7, 7, 20]
8. Tuple()
Syntax:
tuple(<sequences>)
tuple("welcome")
('w', 'e', 'l', 'c', 'o', 'm', 'e')
tuple([1,20])
(1, 20)
Feature are in tuple:
1. You can`t add elements to a tuple because of their immutable property
2. There`s no append() or extend() method for tuples.
3. You can`t remove element from a tuple, also because of their immutability. tuple have no remove() or pop() method.
4. You can find elements from a tuple since this doesn`t change the tuple.
5. You can also use the in operator to check if an element exits in the tuple
6. To change a tuple you can unpack it first, then change the values and pack it again.
7. You can use list() and tuple() methods to change the values of a tuple.
Advantages of using tuples:
l Tuples use less memory whereas lists use more memory.
l We can use tuple in a Dictionary as a key but it is not possible with lists
l We can access element with an index in both tuples and lists.
Disadvantages of using tuples:
l We cannot add an element to a tuple but we can add an element to a list.
l We can`t sort a tuple but in a list we can sort by calling “list.sort()” method.
l We can`t remove an element in a tuple but we can replace in a list.
Download PDF
0 Comments