0% found this document useful (0 votes)
14 views3 pages

Python Tuple Exercises and Solutions

Uploaded by

joyboyshesanand
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views3 pages

Python Tuple Exercises and Solutions

Uploaded by

joyboyshesanand
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Tuple Practice - Q&A

1. Print first, middle, and last item of tuple

tup = ("apple", "banana", "cherry", "orange", "kiwi")

print(tup[0])

print(tup[len(tup)//2])

print(tup[-1])

2. Check if 'banana' exists in the tuple

if "banana" in tup:

print("True")

else:

print("False")

3. Get the length of the tuple

tup = (10, 20, 30, 40)

print(len(tup))

4. Create a single-item tuple and print its type

tup = ("apple",)

print(type(tup))

5. Update a tuple using list conversion

tup = (10, 20, 30, 40)

new_list = list(tup)

new_list[1] = 5

tup = tuple(new_list)

print(tup)

6. Update a tuple by replacing 2 with 20

tup = (1, 2, 3)
new_list = list(tup)

new_list[1] = 20

tup = tuple(new_list)

print(tup)

7. Unpack tuple into 3 variables

tup = ("python", "is", "awesome")

a, b, c = tup

print(a)

print(b)

print(c)

8. Use * in unpacking to collect middle values

tup = (1, 2, 3, 4, 5, 6)

a, *b, c = tup

print(a)

print(b)

print(c)

9. Print only even numbers in tuple

tup = (11, 12, 13, 14, 15, 16)

for x in tup:

if x % 2 == 0:

print(x)

10. Count how many times 5 appears in tuple

tup = (5, 1, 5, 2, 5, 3)

print([Link](5))

11. Join two tuples and sort the result

t1 = (5, 3, 9)
t2 = (1, 6)

t3 = t1 + t2

print(sorted(t3))

12. Nest two tuples and access specific item

t1 = (1, 2)

t2 = (3, 4)

t3 = (t1, t2)

print(t3[1][1])

13. Convert tuple to string

tup = ('H', 'e', 'l', 'l', 'o')

new = "".join(tup)

print(new)

14. Create tuple from range 1 to 10

tup = tuple(x for x in range(1, 11))

print(tup)

15. Create tuple of squares from 1 to 5

new = tuple(x**2 for x in range(1, 6))

print(new)

You might also like