top of page

Python | Tuple

Writer's picture: Priyanshu KanadePriyanshu Kanade

Basically tuple is a list of comma separated values or items between parenthesis

ans it can contain heterogeneous values such as integer, floats, strings, lists and dictionaries.

Python tuples are immutable that is unchangeable and it is a built -in data structure available in python.

Syntax to create a tuple- <variable_name> = ( n1, n2, n3)


Example code to merge two tuples.

t1=(10,20,30,40)
t2=(5,9,12,18,22,25)
t3=[]
i,j,k=0,0,0
while i<len(t1) and j<len(t2):
   if t1[i]<t2[j]:
       t3.append(t1[i])
       i+=1
       k+=1
   else:
       t3.append(t2[j])
       j+=1
       k+=1
if i==len(t1):
    while j<len(t2):
        t3.append(t2[j])
        j+=1
        k+=1
elif j==len(t2):
    while i<len(t1):
        t3.append(t1[i])
        i+=1
        k+=1      
t3=tuple(t3)
print("resulting tuple is:",t3)
Output:
resulting tuple is:(5, 9, 10, 12, 18, 20, 22, 25, 30, 40)
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

7 views0 comments

Recent Posts

See All

Commentaires


bottom of page