A tuple is an immutable object in Python that cannot be changed. Tuples are also sequences, just like Python lists. This Python Tuple exercise aims to help you learn and practice tuple operations.
Also Read:
This Python tuple exercise contains 19 coding questions, each with a provided solution.
- Practice and solve various tuple operations, manipulations, and tuple functions.
- All questions are tested on Python 3.
- Read the complete guide on Python Tuples to solve this exercise.
When you complete each question, you get more familiar with Python tuple. Let us know if you have any alternative solutions. It will help other developers.
Use Online Code Editor to solve exercise questions.
Table of contents
- Exercise 1: Perform Basic Tuple Operations
- Exercise 2: Tuple Repetition
- Exercise 3: Slicing Tuples
- Exercise 4: Reverse the tuple
- Exercise 5: Access Nested Tuples
- Exercise 6: Create a tuple with single item 50
- Exercise 7: Unpack the tuple into 4 variables
- Exercise 8: Swap two tuples in Python
- Exercise 9: Copy Specific Elements From Tuple
- Exercise 10: List to Tuple
- Exercise 11: Function Returning Tuple
- Exercise 12: Comparing Tuples
- Exercise 13: Removing Duplicates from Tuple
- Exercise 14: Filter Tuples
- Exercise 15: Map Tuples
- Exercise 16: Modify Tuple
- Exercise 17: Sort a tuple of tuples by 2nd item
- Exercise 18: Count Elements
- Exercise 19: Check if all items in the tuple are the same
Exercise 1: Perform Basic Tuple Operations
- Create a Tuple: Create a tuple named
my_tuplecontaining the numbers 1, 2, 3, 4, and 5. - Access Elements: Access and print the third element of
my_tuple. - Tuple Length: Find and print the length of
my_tuple.
Expected Output:
My tuple: (1, 2, 3, 4, 5)
The third element of my_tuple: 3
The length of my_tuple: 5
+ Hint
- Create Tuples using parentheses
(). - Use indexing to access elements, meaning the first element is at index 0, the second at index 1, and so on.
- Use the built-in function
len()to find the length of tuple.
+ Show Solution
Exercise 2: Tuple Repetition
Repeat a below tuple three times.
Given:
original_tuple = ('a', 'b')Code language: Python (python)
Expected Output:
('a', 'b', 'a', 'b', 'a', 'b')
+ Hint
Use the * operator to repeat a tuple.
+ Show Solution
Exercise 3: Slicing Tuples
Slice below tuple to get elements from the 4th to the 7th position.
Given:
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)Code language: Python (python)
Expected Output:
(4, 5, 6, 7)
+ Hint
Tuple slicing allows you to extract a portion of a tuple. The syntax [start:end] creates a new tuple containing elements from the start index up to, but not including, the end index.
+ Show Solution
Since we want the 4th to 7th positions, we use index 3 as the start (0-based) and index 7 as the end (because it’s exclusive, it will stop before the 8th element, effectively giving us the 4th, 5th, 6th, and 7th elements).
Exercise 4: Reverse the tuple
Given:
tuple1 = (10, 20, 30, 40, 50)Code language: Python (python)
Expected output:
(50, 40, 30, 20, 10)
Show Hint
Use tuple slicing to reverse the given tuple. Note: the last element starts at -1.
Show Solution
Exercise 5: Access Nested Tuples
Write a code to access and print value 20 from given nested tuple.
Given:
tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))Code language: Python (python)
Expected output:
20
Show Hint
Use double indexing. First, find the index of the inner tuple, then use a second index to find the element within that inner tuple.
Show Solution
Exercise 6: Create a tuple with single item 50
Show Solution
Exercise 7: Unpack the tuple into 4 variables
Write a code to unpack the following tuple into four variables and display each variable.
Given:
tuple1 = (10, 20, 30, 40)Code language: Python (python)
Expected output:
tuple1 = (10, 20, 30, 40)
# Your code
print(a) # should print 10
print(b) # should print 20
print(c) # should print 30
print(d) # should print 40
+ Hint
You can assign multiple variables to a tuple directly, provided the number of variables matches the number of elements in the tuple.
Show Solution
Exercise 8: Swap two tuples in Python
Given:
tuple1 = (11, 22)
tuple2 = (99, 88)Code language: Python (python)
Expected output:
tuple1: (99, 88) tuple2: (11, 22)
Show Solution
Exercise 9: Copy Specific Elements From Tuple
Write a program to copy elements 44 and 55 from the following tuple into a new tuple.
Given:
tuple1 = (11, 22, 33, 44, 55, 66)Code language: Python (python)
Expected output:
tuple2: (44, 55)
Show Solution
Exercise 10: List to Tuple
Convert a list my_list = [10, 20, 30] into a tuple.
Expected Output:
(10, 20, 30)
+ Show Solution
Exercise 11: Function Returning Tuple
Write a function get_min_max(numbers) that takes a list of numbers and returns a tuple containing the minimum and maximum number.
Given:
def get_min_max(numbers):
# Write your code here
# Test the function
my_numbers = [10, 5, 20, 2, 15]
min_max_values = get_min_max(my_numbers)
print(f"Original numbers: {my_numbers}")
print(f"Minimum and maximum values: {min_max_values}")Code language: Python (python)
Expected Output:
Original numbers: [10, 5, 20, 2, 15]
Minimum and maximum values: (2, 20)
+ Hint
- Use the built-in
min()andmax()functions that can be directly applied to a list. - Functions can return multiple values by separating them with commas, which implicitly creates a tuple.
+ Show Solution
Exercise 12: Comparing Tuples
Compare two tuples and find out which one is “greater” and why?
Given:
t1 = (1, 2, 3)
t2 = (1, 2, 4)Code language: Python (python)
Expected Output:
Tuple 1: (1, 2, 3, 8)
Tuple 2: (1, 2, 4, 5)
(1, 2, 3, 8) is less than (1, 2, 4, 5)
+ Hint
Python compares tuples lexicographically (element by element) from left to right. The first pair of elements that differ determines the outcome.
+ Show Solution
Explanation:
Python compares tuples element by element.
- It compares
t1[0](which is 1) witht2[0](which is 1). They are equal. - It then moves to
t1[1](which is 2) andt2[1](which is 2). They are also equal. - Finally, it compares
t1[2](which is 3) witht2[2](which is 4). Since3 < 4, Python determines thatt1is less thant2
Exercise 13: Removing Duplicates from Tuple
Write a code to create a new tuple with only unique elements.
Given:
my_tuple = (1, 2, 2, 3, 4, 4, 5)Code language: Python (python)
Expected Output:
Original tuple with duplicates: (1, 2, 2, 3, 4, 4, 5)
Tuple with unique elements: (1, 2, 3, 4, 5)
+ Hint
Sets in Python inherently store only unique elements. You can convert the tuple to a set to remove duplicates, and then convert it back to a tuple. Note that sets do not preserve order.
+ Show Solution
Solution 2: If preserving original order of first appearance is important:
Exercise 14: Filter Tuples
Write a code to filter out students with scores less than 90 from a given a list of tuples.
Given:
students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]Code language: Python (python)
Expected Output:
Students with scores 90 or above: [('Bob', 92), ('David', 95)]
+ Hint
Use a loop with a conditional statement, or a list comprehension with a condition. Access the score (the second element) of each student tuple.
+ Show Solution
Solution 1: Using loop
Solution 2: Using list comprehension
Exercise 15: Map Tuples
Given a tuple of numbers, create a new tuple where each number is squared.
Given:
t = (1, 2, 3, 4)Code language: Python (python)
Expected Output:
Original tuple: (1, 2, 3, 4)
Squared tuple: (1, 4, 9, 16)
+ Hint
Use a loop, a list comprehension (and then convert to tuple), or the map() function with a lambda expression or a regular function. The map() function is often used for applying a function to each item in an iterable.
+ Show Solution
Solution 1: Using map() and tuple()
Solution 2: Using a loop
Exercise 16: Modify Tuple
Given is a nested tuple. Write a program to modify the first item (22) of a list inside a following tuple to 222
Given:
tuple1 = (11, [22, 33], 44, 55)Code language: Python (python)
Expected output:
tuple1: (11, [222, 33], 44, 55)
Show Hint
The given tuple is a nested tuple. Use indexing to locate the specified item and modify it using the assignment operator.
Show Solution
Exercise 17: Sort a tuple of tuples by 2nd item
Given:
tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))Code language: Python (python)
Expected output:
(Sorted tuple by 2nd item: (('c', 11), ('a', 23), ('d', 29), ('b', 37))
+ Hint
Tuples are immutable, so you cannot sort them directly. You’ll need to convert the tuple to a list first, sort the list, and then optionally convert it back to a tuple.
Show Solution
Exercise 18: Count Elements
Write a code to counts the number of occurrences of item 50 from a tuple.
Given:
tuple1 = (50, 10, 60, 70, 50)Code language: Python (python)
Expected output:
2
Show Hint
Use the count() method of a tuple.
Show Solution
Exercise 19: Check if all items in the tuple are the same
tuple1 = (45, 45, 45, 45)Code language: Python (python)
Expected output:
True

Exercise 17: Sort a tuple of tuples by 2nd item
My python version is 3.13.3, the following codes done, i.e., sorted the tuple directly without changing to list type.
# Exercise 17: Sort a tuple of tuples by 2nd item
tuple1 = ((‘a’, 23),(‘c’, 11), (‘b’, 37),(‘d’,29))
sorted_tuple = tuple(sorted(tuple1, key=lambda x: x[1]))
print(f”Original tuple: {tuple1}”)
print(f”Sorted tuple by 2nd item: {sorted_tuple}”)
Thank you, Vishal, for creating this website and simplifying complex concepts and topics in an easily understandable manner. I have bookmarked your website, and whenever I encounter any issues or doubts, I refer to the relevant topic on your site for assistance. Once again, thank you very much.
Another answer for number 10 , may be
tuple1 = (45, 45, 45, 45)
print(all(tuple1))
No because if you change any of the 45 to any other non zero value, it’ll still give True as all gives true if all values are non zero and not necessary same
Q 10. Another solution:
tuple1 = (45, 45, 45, 45)
print(all(tuple1))
Same answer as mine
It is showing error when we are putting an extra value i.e 46 in the tuple then also it is giving True which is wrong.
tuple1 = (45, 45, 45, 45,46)
print(all(tuple1))
it should return False but giving output as True.
It always gave the output as True, untill you give 0 as elements in the tuple.
tuple1 = (45, 76, 98, 53, 0)
print(all(tuple1))
only this tuple gives you the output as ‘False’, otherwise you get ‘True’ for every possibility.
Another solution for exercise 10 :
tuple1 = (45, 45, 45, 45)
if tuple1.count(tuple1[0]) == len(tuple1):
print(“are all the same”)
else:
print(“are all not the same”)
i have an other solution
tuple1 = (45, 45, 45, 45)
a, b, c, d = tuple1
print(a is b is c is d)
#it is not that good but it does the job
Super it works for me.
what if we have 100 or 1000 values?
def is_same_elems(tpl):
return len(set(tpl)) == 1
Great idea!
tuple1 = (45, 45, 45, 45)
if len(set(tuple1))==1:
print(“same”)
else:
print(“not same”)
thank you so much, that was very helpful
Create a pandas dataframe from list of marks of semester 1, 2, 3, and 4, which are given below and index them as Maths, Physics, and Chemistry.
Semester 1: [84, 99, 95]
Semester 2: [70, 89, 85]
Semester 3: [85, 90, 92]
Semester 4: [91, 87, 79]
print non repeated integer from the list.
numbers=[2,4,2,3,4,6,3,7,6]
from collections import Counternumbers=[2,4,2,3,4,6,3,7,6]
new_numbers = Counter(numbers)
n = [number[0] for number in new_numbers.items() if number[1] < 2]
print(n)
Thanks for the response but I got error as (No module named ‘counter’)
def print_non_repeated_elems(nums):
return [i_el for i_el in nums if nums.count(i_el) == 1]
for i in numbers:if numbers.count(i) == 1:
print(i)
numbers=[2,4,2,3,4,6,3,7,6]L=[]
for i in numbers:
if numbers.count(i)>1:
continue
else:
L.append(i)
print(L)
set={2,4,2,3,4,6,3,7,6}
print(list(set))
[(‘a’,50),(‘b’,60),(‘c’,40)] , get the values in descending order
o/p=[‘b’,’a’,’c’]
list1 = [('a', 50), ('b', 60), ('c', 40)]new_list = [x[0] for x in (sorted(list1, key=lambda x: x[1], reverse=True))]
print(new_list)
Thank you
Exercise 6 – alternative approach (please re-insert pre tags if these are stripped)
tuple1 = (11, 22, 33, 44, 55, 66)def copy_elements_tuple(*elements):
new_tuple = (elements)
print(new_tuple)
copy_elements_tuple(44,55)
pls guide how to use to comment a code?
If you are using vs code then click “ctrl + /”.
For single line comment use “#” and for multiline comment use
”’
this is inside multiline comment
”’
Exercise 8
tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))sorted_tuple = tuple(sorted(tuple1,key=lambda x:x[1]))
print(sorted_tuple)
EX6: Copy Specific elements
tuple1 = (11, 22, 33, 44, 55, 66)/tuple2 = tuple()
for i in tuple1:
if i == 44 or i == 55:
tuple2 += i,
print(tuple2)
Make sure we have a comma after i in for loop
Suppose i want to copy 44 and 55
Use the slice method to decrease no.of lines.
tuple2 = tuple1[3:5]print(tuple2)
output:
(44,55)For exercise 6:
tuple1=[11,22,33,44,55,66]I think the solution would be
tuple2=tuple1[-3:-1]or
tuple2=tuple1[3:5]Above program why we use -1
negative indexing is used we when we used index from right side
this happens same with string, list and tuple data types.
we can use negative indexing or positive indexing
when we count from right to left indexing start from -1 and so on, but when we count from left to right we use positive indexing 0 and so on….
Hope you understand….
simple formula in case of negative
tuple2=tuple1[len(tuple1)-3:len(tuple1)-1]=tuple1[6-3:6-1]=tuple1[3:5]For Exercise 7, i don’t think we can modify tuple directly as Tuple is unchangeable. For updation or modification, tuple needs to be converted to list, update the changes and revert back
is this correct??
True
This solution to Ex. 10 seems much simpler and straightforward.
agreed. I took the same approach.
Another solution for question 10
This is my answer for Q10
Q10
Nice one!
I don’t believe it’s the correct solution. this logic works only for tuples with item 1.
Another solution for exercise 10:
Here is my solution for exercise 10
# Exercise 10: Check if all items in the tuple are the sametuple1 = (45, 45, 45, 45)
a = tuple1.count(tuple1[0])
if(a==len(tuple1)):
print(True)
else:
print(False)
Another solution for exercise 8:
Another solution for exercise 8:
Exercise 6:
You can add it directly to new tuple
# tuple1 = (11, 22, 33, 44, 66, 55)# tuple2 = tuple()
# for i in tuple1:
# if i == 44 or i == 55:
# tuple2 += i,
Make sure you don’t forget the comma after += I in if the loop
What does
lambda x: x[1]mean?Sorted function is mapping iterable to lambda and then sorting it out.
so Lambda takes x as argument to which element from iterable that is tuple1 is being supplied which is a tuple i.e. for first iteration (‘a’,23) and so on. So to access number from it indexing of x is done i.e. x[1]. and at the end sorting is applied on this number.
i think this is better than your solution what do you think ?
the solution for exercise 8 went over my head as i have still not learnt lamda expressions well. My solution was:
how much time do you guys take on an average to solve exercises in pynative??
Hi
exercise5 has second solution:
as a developer you are required to do tasks efficiently in less time and less lines of codes to be written
This code also works
but it will print (True True True True False) maybe we should try something like while loop. How about this?
Ps: sorry not a while loop, just a condition in the start.
Hi,Vishal!
Very useful website and good quality content…
Your website helps strength my basis in python….
Thanks a lot!
I think its a good solution for Exercise 10
Thanks for useful exercises. How about below syntax for Exercise 10
Very useful site… but it would have been even better if you provided an explanation after each solution
Thank you for the suggestion, Yes we will definitely add an explanation.
Hi Vishal!
Most of signs are very clear and nice. And all can be learned using only Your homepage.
Thanks a lot!
Thank you, Marton.
I think It is a good solution. It’s working for all variants.
Another solution to question 10:
This already works,
I’m not sure the if statement part is useful here. Great solution though
good work
Hey,Vishal I’m Gulshan and want to really appericate for making this website because it helped me in working on basics of python which is very necessary to learn before moving forward with any language.
I had learnt python basics from Coursera and trust me most of the thing i saw here, wasn’t covered in coursera. Thank you 🙂
I am glad you liked it
Hi Vishal, same here, I learnt from Codecademy,
When I came across your blog, I felt like I had learnt nothing so far. Restarted everything from scratch.
Thank you so much and great work.
Thank you, Danilo.
SR: if you pass empty tuple, it will show Index Error
what about this code. is this correct way or wrong way for best programmer
Not All value are same
Hi Vishal, I’ve been learning Python for about 6 months and I am flustered. I don’t know any programmers but a few videos I’ve subscribed to on Youtube. I’ve have tried to research google for myself and discovered you. I was working with Udemy and kept getting confused. I am trying to write a simple program for myself. I want to randomly select a file from a directory, yet I am hitting a wall. I have Python 3.7 and here is my sample.
import os import random d = os.getcwd() parent = os.path.join(d, "....") d1 = os.path.join(d, "utils") d2 = os.path.join(d1,"tao") path = (r"C:\Users\MyNameDEW\Desktop\TaoFinalProject.py\utils\tao") tuple = tao_list = [(("Test_tao.txt",0),("1_tao.txt",1),("2_tao.txt",2),("3_tao.txt",3),("4_tao.txt",4),("5_tao.txt",5))] print("Random element from tuple:",random.choice(tao_list)) fname = random.choice(tao_list) f = open(fname, 'r', encoding='utf-8') for l in f: print(l, end="")My results: TypeError: expected str, bytes, or os.PathLike object, not a tuple
Hey, Derrick, you can try this code
import os import random # change to your path path = 'E:\\pynative\\Python\\' # list all files files = [] # r=root, d=directories, f = files for r, d, f in os.walk(path): for file in f: if '.txt' in file: files.append(os.path.join(r, file)) # print all file names for f in files: print(f) # choose random file randomFile = random.choice(files) print("random file") print(randomFile) # read selected file f = open(randomFile, 'r', encoding='utf-8') for l in f: print(l, end="")WIll this work???
tuple1 = (45, 45, 45, 45) if len(tuple1) == tuple1.count(45): return True else: return Falsethis is working Keerthi
sry, there should be indentations in those print statements
It is a good solution for example 10?
I have tried below the solution for Question No.10, Please let me know if its correct way to check
tuple1 = (45, 45, 45, 45) tuple2 = tuple1[::-1] if tuple1 == tuple2: print("True") else: print("False")Hey, Nupur, this will also work, but the solution you provided is not efficient when tuple contains more elements. Thank you
Nupur: Wrong: Solution Try with tuple1 = (45,46,46,45)
The solution (or task) in Exercise Question 10 is wrong. It will return true even if values are different:
Output:
TrueAlex, You are right. Now, I have updated the answer. Can you please check
Another solution:
tuple1 = (45, 45, 45, 45) if len(set(tuple1)) == 1: print(True)SR: If you pass empty tuple, your solution will show IndexError
Oops, I take that back. I had another issue.