#7 Python:- Tuple
Tuple:-
It can be created by writing all the element inside parentheses () separated by commas.
e.q :- mytuple=(1,2,3)
print(mytuple) ------> (1, 2, 3)
Note:- Tuple are faster than list.
Properties:-
i) Immutable:- It means we can't assign or change values of tuple.
e.q :- tup=(1, 5, 9, 2)
tup[2]=15
print(tup) ----> Error
Because we can't change the value inside the tuple since it is immutable.
ii) Ordered:- We can do slicing and indexing
Indexing:- tup=(15, 8, 12, 18, 20.5)
print(tup[1]) ---->8
Slicing:-
print(tup[1:4])----> (8, 12, 18)
Some other syntax for tuple:-
i) .count:- It counts numbers of times the same digit or character comes.
e.q. :- tup=(15, 8, 12, 18, 20.5. 8)
tup.count('8') ----> 2
tup.count('12') ----> 1
tup.count('22') ----> 0
ii) .index:- It is used for locating the position of specific digit when it comes for the first time.
tup=(15, 8, 12, 18, 20.5)
tup.index('12') ----> 2
Defining tuple with one element:-
tup= (1)
word=('Gurpreet')
print(type(tup)) ----> int #we can't create tuple with one element by parenthesis
print(type(words)) ----> str #we can't create tuple with one element by parenthesis
To do so
tup=(1,) # Comma ( , ) is must for one element to let python know that it is tuple.
word= ('Gurpreet',)
print(type(tup)) -----> Tuple
print(type(word)) -----> Tuple
Tuple without parenthesis:-
words= 'Guri' , 'Jaat' , 'Madhu'
print(type(words)) -----> Tuple
Note:- By default it is tuple
Tuple Unpacking:-
tup= ('monu', 'sonu' ,'mohit')
first, second, third = tup
print(first) ---> monu
print(fsecond) ---> sonu
print(third) ---> mohit
Note:- Numbers of Variables always need to equal to length of tuple.
List Inside Tuple:-
tup= ('monu', ['sonu' ,'mohit'])
tup[1].pop() ----> ('monu', ['sonu' ])
Note:- We can add or delete list inside a tuple.
Function returning two value :-
def func(a,b):
add= a+b
multiply= a*b
return add, multiply
print(func(2,3))
add,multiply = func(2,3)
print(add)
print(multiply)
Output:-
(5, 6) #it return in form of tuple
5
6
Comments
Post a Comment