PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Tuple Exercise with Solutions

Python Tuple Exercise with Solutions

Updated on: June 3, 2025 | 101 Comments

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:

  • Python Tuples
  • Python Tuple Quiz

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

  1. Create a Tuple: Create a tuple named my_tuple containing the numbers 1, 2, 3, 4, and 5.
  2. Access Elements: Access and print the third element of my_tuple.
  3. 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
# 1. Create a Tuple
my_tuple = (1, 2, 3, 4, 5)
print(f"My tuple: {my_tuple}")

# 2. Access Elements
third_element = my_tuple[2] # Index 2 corresponds to the third element
print(f"The third element of my_tuple: {third_element}")

# 3. Tuple Length
tuple_length = len(my_tuple)
print(f"The length of my_tuple: {tuple_length}")Code language: Python (python)

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
original_tuple = ('a', 'b')
repeated_tuple = original_tuple * 3
print(f"Repeated tuple: {repeated_tuple}")Code language: Python (python)

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
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Slice from the 4th position (index 3) up to (but not including) the 8th position (index 7)
sliced_numbers = numbers[3:7]
print(f"Sliced tuple: {sliced_numbers}")Code language: Python (python)

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
tuple1 = (10, 20, 30, 40, 50)
tuple1 = tuple1[::-1]
print(tuple1)Code language: Python (python)

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
tuple1 = ("Orange", [10, 20, 30], (5, 15, 25))

# understand indexing
# tuple1[0] = 'Orange'
# tuple1[1] = [10, 20, 30]
# list1[1][1] = 20

print(tuple1[1][1])Code language: Python (python)

Exercise 6: Create a tuple with single item 50

Show Solution
tuple1= (50, )
print(tuple1)Code language: Python (python)

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
tuple1 = (10, 20, 30, 40)

# unpack tuple into 4 variables
a, b, c, d = tuple1
print(a)
print(b)
print(c)
print(d)Code language: Python (python)

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
tuple1 = (11, 22)
tuple2 = (99, 88)
tuple1, tuple2 = tuple2, tuple1
print(tuple2)
print(tuple1)Code language: Python (python)

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
tuple1 = (11, 22, 33, 44, 55, 66)
tuple2 = tuple1[3:-1]
print(tuple2)Code language: Python (python)

Exercise 10: List to Tuple

Convert a list my_list = [10, 20, 30] into a tuple.

Expected Output:

(10, 20, 30)
+ Show Solution
my_list = [10, 20, 30]

# Use the tuple() constructor to convert the list
converted_tuple = tuple(my_list)
print(f"Converted list to tuple: {converted_tuple}")Code language: Python (python)

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() and max() 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
def get_min_max(numbers):
    if not numbers:
        return (None, None) # Handle empty list case
    
    min_val = min(numbers)
    max_val = max(numbers)
    return (min_val, max_val)

# 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)

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
t1 = (1, 2, 3)
t2 = (1, 2, 4)

print(f"Tuple 1: {t1}")
print(f"Tuple 2: {t2}")

if t1 > t2:
    print(f"{t1} is greater than {t2}")
elif t1 < t2:
    print(f"{t1} is less than {t2}")
else:
    print(f"{t1} is equal to {t2}")Code language: Python (python)

Explanation:

Python compares tuples element by element.

  1. It compares t1[0] (which is 1) with t2[0] (which is 1). They are equal.
  2. It then moves to t1[1] (which is 2) and t2[1] (which is 2). They are also equal.
  3. Finally, it compares t1[2] (which is 3) with t2[2] (which is 4). Since 3 < 4, Python determines that t1 is less than t2

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
my_tuple = (1, 2, 2, 3, 4, 4, 5)
print(f"Original tuple with duplicates: {my_tuple}")

# Convert to a set to remove duplicates (order is not preserved)
unique_elements_set = set(my_tuple)

# Convert back to a tuple
unique_tuple = tuple(unique_elements_set)
print(f"Tuple with unique elements: {unique_tuple}")Code language: Python (python)

Solution 2: If preserving original order of first appearance is important:

from collections import OrderedDict
my_tuple = (1, 2, 2, 3, 4, 4, 5)
print(f"Original tuple with duplicates: {my_tuple}")

unique_ordered_tuple = tuple(OrderedDict.fromkeys(my_tuple))
print(f"Tuple with unique elements (order preserved): {unique_ordered_tuple}")Code language: Python (python)

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

students = [('Alice', 85), ('Bob', 92), ('Charlie', 78), ('David', 95)]
print(f"Original student list: {students}")

high_achievers_loop = []
for student in students:
  if student[1] >= 90:
    high_achievers_loop.append(student)
print(f"Students with scores 90 or above (loop method): {high_achievers_loop}")Code language: Python (python)

Solution 2: Using list comprehension

students = [('Alice', 85), ('Bob', 92), ('Charlie', 78), ('David', 95)]
print(f"Original student list: {students}")

# Using a list comprehension for filtering
# For each student tuple, check if their score (student[1]) is >= 90
high_achievers = [student for student in students if student[1] >= 90]
print(f"Students with scores 90 or above: {high_achievers}")Code language: Python (python)

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()

t = (1, 2, 3, 4)
print(f"Original tuple: {t}")

# Method 1: Using map() and tuple()
squared_tuple_map = tuple(map(lambda x: x**2, t))
print(f"Squared tuple (map function): {squared_tuple_map}")Code language: Python (python)

Solution 2: Using a loop

# 7. Map Tuples
t = (1, 2, 3, 4)
print(f"Original tuple: {t}")

# Method 2: Using a loop
squared_list_loop = []
for num in t:
  squared_list_loop.append(num ** 2)
  squared_tuple_loop = tuple(squared_list_loop)
print(f"Squared tuple (loop): {squared_tuple_loop}")Code language: Python (python)

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
tuple1 = (11, [22, 33], 44, 55)
tuple1[1][0] = 222
print(tuple1)Code language: Python (python)

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
# 1. Sort a tuple by 2nd item
tuple1 = (('a', 23), ('b', 37), ('c', 11), ('d', 29))
print(f"Original tuple: {tuple1}")

# Convert the tuple to a list because tuples are immutable and cannot be sorted in-place
list1 = list(tuple1)

# Sort the list using the 'sorted()' function with a lambda key
# The lambda function `lambda item: item[1]` tells sorted() to use the second element
# (index 1) of each inner tuple for comparison.
sorted_list = sorted(list1, key=lambda item: item[1])

# If you need the result back as a tuple, convert the sorted list back to a tuple
sorted_tuple = tuple(sorted_list)

print(f"Sorted tuple by 2nd item: {sorted_tuple}")Code language: Python (python)

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
tuple1 = (50, 10, 60, 70, 50)
print(tuple1.count(50))Code language: Python (python)

Exercise 19: Check if all items in the tuple are the same

tuple1 = (45, 45, 45, 45)Code language: Python (python)

Expected output:

True

Show Solution
def check(t):
    return all(i == t[0] for i in t)

tuple1 = (45, 45, 45, 45)
print(check(tuple1))
Code language: Python (python)

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Imageharry says

    July 12, 2025 at 6:38 am

    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}”)

    Reply
  2. ImageSachin Kashyap says

    March 2, 2024 at 1:29 am

    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.

    Reply
  3. ImageSayi says

    November 29, 2023 at 6:53 pm

    Another answer for number 10 , may be

    tuple1 = (45, 45, 45, 45)
    print(all(tuple1))

    Reply
    • ImageIdrees says

      June 30, 2024 at 12:47 am

      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

      Reply
  4. Imagefateme says

    November 18, 2023 at 10:06 am

    Q 10. Another solution:

    tuple1 = (45, 45, 45, 45)

    print(all(tuple1))

    Reply
    • ImageSayi says

      November 29, 2023 at 6:53 pm

      Same answer as mine

      Reply
    • ImageAjay Kaushik says

      March 18, 2024 at 4:12 pm

      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.

      Reply
      • ImageSOUMYA GHOSH says

        November 7, 2025 at 10:52 am

        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.

        Reply
  5. ImageAmir says

    August 31, 2023 at 2:56 pm

    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”)

    Reply
    • Imagedhia says

      November 8, 2023 at 5:11 pm

      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

      Reply
      • ImageScott hollland says

        April 13, 2024 at 3:53 pm

        Super it works for me.

        Reply
      • ImageDeepak says

        June 4, 2024 at 11:49 pm

        what if we have 100 or 1000 values?

        Reply
    • Imageromankrv says

      December 8, 2023 at 5:48 pm

      def is_same_elems(tpl):
      return len(set(tpl)) == 1

      Reply
    • ImageOkbazghi says

      February 2, 2025 at 12:37 am

      Great idea!

      Reply
    • ImageAbhi says

      September 28, 2025 at 9:55 pm

      tuple1 = (45, 45, 45, 45)
      if len(set(tuple1))==1:
      print(“same”)
      else:
      print(“not same”)

      Reply
  6. ImageMohammadHO3ein Hahsemi says

    August 24, 2023 at 12:04 pm

    thank you so much, that was very helpful

    Reply
  7. ImageMatla Avinash says

    May 10, 2023 at 7:15 pm

    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]

    Reply
  8. ImageMatla Avinash says

    May 9, 2023 at 8:18 pm

    print non repeated integer from the list.
    numbers=[2,4,2,3,4,6,3,7,6]

    Reply
    • ImageEmilio says

      May 10, 2023 at 4:24 am

      from collections import Counter

      numbers=[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)

      Reply
      • ImageMatla Avinash says

        May 10, 2023 at 7:18 pm

        Thanks for the response but I got error as (No module named ‘counter’)

        Reply
        • Imageromankrv says

          December 8, 2023 at 5:57 pm

          def print_non_repeated_elems(nums):
          return [i_el for i_el in nums if nums.count(i_el) == 1]

          Reply
    • ImageAIyman says

      June 15, 2023 at 1:11 pm

      for i in numbers:
      if numbers.count(i) == 1:
      print(i)

      Reply
    • ImageNanu vel says

      July 2, 2023 at 6:34 pm

      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)

      Reply
    • ImageSr1kanth says

      October 20, 2024 at 3:17 pm

      set={2,4,2,3,4,6,3,7,6}
      print(list(set))

      Reply
  9. ImageMatla Avinash says

    May 9, 2023 at 8:16 pm

    [(‘a’,50),(‘b’,60),(‘c’,40)] , get the values in descending order
    o/p=[‘b’,’a’,’c’]

    Reply
    • ImageEmilio says

      May 10, 2023 at 5:08 am

      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)

      Reply
      • ImageMatla Avinash says

        May 10, 2023 at 7:09 pm

        Thank you

        Reply
  10. Imagevini1955 says

    November 5, 2022 at 5:15 am

    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)

    Reply
  11. ImageKhan says

    November 4, 2022 at 7:56 am

    pls guide how to use to comment a code?

    Reply
    • ImageAkash says

      March 28, 2023 at 2:28 pm

      If you are using vs code then click “ctrl + /”.
      For single line comment use “#” and for multiline comment use
      ”’
      this is inside multiline comment
      ”’

      Reply
  12. ImageKhan says

    November 4, 2022 at 7:55 am

    Exercise 8

    tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))
    sorted_tuple = tuple(sorted(tuple1,key=lambda x:x[1]))
    print(sorted_tuple)

    Reply
  13. ImageTuanNG says

    October 27, 2022 at 8:08 pm

    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)
    /

    Reply
    • ImageTuanNG says

      October 27, 2022 at 8:11 pm

      Make sure we have a comma after i in for loop

      Reply
    • ImageA vinay kalyan reddy says

      November 14, 2022 at 7:24 pm

      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)

      Reply
  14. ImageSR says

    October 21, 2022 at 3:34 pm

    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]

    Reply
    • ImageSravani says

      February 2, 2023 at 6:00 pm

      Above program why we use -1

      Reply
      • ImageShahzad Ahmad says

        March 3, 2023 at 5:50 pm

        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….

        Reply
    • ImageMuhammad Ramzan says

      June 17, 2023 at 3:37 pm

      simple formula in case of negative
      tuple2=tuple1[len(tuple1)-3:len(tuple1)-1]=tuple1[6-3:6-1]=tuple1[3:5]

      Reply
  15. ImageSR says

    October 21, 2022 at 3:30 pm

    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

    Reply
  16. ImageBhuvi Sakthi says

    September 4, 2022 at 9:59 am

    is this correct??

    tuple1 = (45, 45, 45, 45)
    result=all(tuple1)
    print(result)

    True

    Reply
    • ImageThangavel says

      September 12, 2022 at 10:56 pm

      tuple1 = (45, 45, 45, 45)
      result=  tuple1 == tuple1
      print(result)
      Reply
      • ImageThangavel says

        September 13, 2022 at 10:36 am

        tuple2 = (100, 100, 100,100)
        
        def match(tuple1):
            index = 0
            for i in tuple1:
                index = index +1
                if index ==len(tuple1):
                    return True 
                if i == tuple1[0]:
            
                    continue
                else:
                    return False
                
        a = match(tuple2)   
        print(a)
        Reply
  17. ImageDavid says

    August 24, 2022 at 8:33 pm

    This solution to Ex. 10 seems much simpler and straightforward.

    tuple1 = (45, 45, 45, 45)
    myset = set(tuple1)
    print(len(myset) == 1)
    Reply
    • ImageBob says

      September 2, 2022 at 2:55 pm

      agreed. I took the same approach.

      Reply
  18. ImageDomey_Eben says

    August 20, 2022 at 2:00 pm

    Another solution for question 10

    
    tuple1 = (45, 45, 45, 45)
    a = tuple1[1]
    print(tuple1.count(a) == len(tuple1))
    Reply
  19. ImageNassim says

    July 22, 2022 at 3:34 pm

    This is my answer for Q10

    tuple1 = (45, 45, 45, 45)
    
    def same_items(c):
        return len(c) == c.count(c[0])
    
    print(same_items(tuple1))
    Reply
  20. ImageSerkan says

    July 17, 2022 at 2:03 pm

    Q10

    tuple1 = (45, 45, 45, 45)
    
    c = lambda x, y: True if x.count(y) == len(x) else False
    
    print(c(tuple1, 45))
    Reply
    • ImageIvan says

      September 29, 2022 at 11:23 pm

      Nice one!

      Reply
  21. Imagerayhon says

    June 13, 2022 at 6:31 pm

    t=(1,1,1)
    flag=0
    for i in t:
      if i!=1:
        flag+=1
        print('false')
      else:
        print('true')
    Reply
    • Imagebob says

      September 2, 2022 at 3:00 pm

      I don’t believe it’s the correct solution. this logic works only for tuples with item 1.

      Reply
  22. ImageAbdou says

    June 8, 2022 at 12:19 am

    Another solution for exercise 10:

    tuple1 = (45, 45, 45, 45)
    start=0
    true=0
    while start<len(tuple1)-1:
        if tuple1[start]==tuple1[start+1]:
            start+=1
            true+=1
    if true==len(tuple1)-1:
        print(True)
    Reply
    • ImageAkash says

      March 28, 2023 at 2:32 pm

      Here is my solution for exercise 10
      # Exercise 10: Check if all items in the tuple are the same
      tuple1 = (45, 45, 45, 45)
      a = tuple1.count(tuple1[0])
      if(a==len(tuple1)):
      print(True)
      else:
      print(False)

      Reply
  23. ImageAbdou says

    June 7, 2022 at 11:49 pm

    Another solution for exercise 8:

    tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))
    a=[]
    b=[]
    c=[]
    for i,j in tuple1:
        a.append(i)
        b.append(j)
    b.sort()
    for y,n in zip(a,b):
       c.append((y,n))
    print(c)
    Reply
  24. ImageAbdou says

    June 7, 2022 at 12:52 pm

    Another solution for exercise 8:

    tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))
    a=list(tuple1)
    a[0],a[1],a[2],a[3]=a[2],a[0],a[3],a[1]
    print(tuple(a))
    Reply
  25. ImageRishikesh Shah says

    April 1, 2022 at 10:01 am

    Exercise 6:

    tuple1 = (11, 22, 33, 44, 55 ,66)
    list1 =list(tuple1)
    new_list = []
    
    for i in list1:
        if i == 44 or i == 55:
            new_list.append(i)
    new_tuple = tuple(new_list)
    print(new_tuple)
    Reply
    • ImageTuanNG says

      October 27, 2022 at 8:17 pm

      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

      Reply
  26. ImageDIvya says

    March 6, 2022 at 3:04 pm

    What does lambda x: x[1] mean?

    Reply
    • ImagePraful Thube says

      June 6, 2022 at 6:30 pm

      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.

      Reply
  27. ImageJosh says

    January 21, 2022 at 4:36 pm

    tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))
    tuple1_sorted = sorted(tuple1,key=lambda x: x[1])
    print(tuple1_sorted)

    i think this is better than your solution what do you think ?

    Reply
  28. ImageBernard says

    January 8, 2022 at 10:44 am

    the solution for exercise 8 went over my head as i have still not learnt lamda expressions well. My solution was:

    
    tuple1 = (('a', 23),('b', 37),('c', 11), ('d',29))
    s = []
    newtuple = ()
    for n,t in tuple1:
        s.append(t)   
    s.sort()
    for i in s:
        for x,y in tuple1:
            if i == y:
                newtuple += (x,y)
    newtuple
    Reply
    • ImageJacob says

      July 3, 2022 at 6:05 pm

      how much time do you guys take on an average to solve exercises in pynative??

      Reply
  29. ImageMajid says

    December 29, 2021 at 5:21 pm

    Hi
    exercise5 has second solution:

    tuple1 = (11, 22)
    tuple2 = (99, 88)
    a = tuple1
    tuple1 = tuple2
    tuple2 = a
    print(tuple1)
    print(tuple2)
    Reply
    • ImageRitik Gupta says

      April 6, 2022 at 5:39 pm

      as a developer you are required to do tasks efficiently in less time and less lines of codes to be written

      Reply
  30. ImageGanesh says

    October 15, 2021 at 7:04 pm

    tuple1 = (45, 45, 45, 45, 50)
    for i in tuple1:
        if i == 45:
            print("True")
        else:
            print("False")

    This code also works

    Reply
    • ImageGilfoyle says

      October 26, 2021 at 3:08 pm

      but it will print (True True True True False) maybe we should try something like while loop. How about this?

      condition = True 
      tuple1 = (45, 45, 45, 45,) 
      for i in tuple1:
          if i!= 45:
              condition=False
      print (condition)
      Reply
      • ImageGilfoyle says

        October 26, 2021 at 3:09 pm

        Ps: sorry not a while loop, just a condition in the start.

        Reply
  31. ImageHARIHARAN G T S says

    May 5, 2021 at 9:05 pm

    Hi,Vishal!
    Very useful website and good quality content…
    Your website helps strength my basis in python….
    Thanks a lot!

    Reply
  32. ImageFilipe says

    March 24, 2021 at 8:56 pm

    I think its a good solution for Exercise 10

    if tuple1.count(45) == len(tuple1):
        print(True)
    Reply
    • ImageAakash says

      May 31, 2021 at 5:52 am

      Thanks for useful exercises. How about below syntax for Exercise 10

      print(len(pd.unique(tuple1))==1)
      Reply
  33. Imageashaar says

    March 8, 2021 at 9:32 pm

    Very useful site… but it would have been even better if you provided an explanation after each solution

    Reply
    • ImageVishal says

      March 9, 2021 at 8:08 pm

      Thank you for the suggestion, Yes we will definitely add an explanation.

      Reply
  34. ImageMarton says

    February 27, 2021 at 2:07 am

    Hi Vishal!
    Most of signs are very clear and nice. And all can be learned using only Your homepage.
    Thanks a lot!

    Reply
    • ImageVishal says

      March 2, 2021 at 8:53 pm

      Thank you, Marton.

      Reply
  35. ImageNick says

    February 14, 2021 at 1:02 am

    I think It is a good solution. It’s working for all variants.

    tuple1 = (45, 45, 45, 45)
    len(tuple1)==tuple1.count(tuple1[0])
    Reply
  36. ImageLuis says

    February 8, 2021 at 2:06 am

    Another solution to question 10:

    tuple1 = (45, 45, 45, 45)
    print(min(tuple1) == max(tuple1) if tuple1 else 'No data to check')
    Reply
    • ImageDanilo says

      December 24, 2021 at 5:22 pm

      This already works,

      
      print(min(tuple1) == max(tuple1))

      I’m not sure the if statement part is useful here. Great solution though

      Reply
  37. Imagepatience says

    December 24, 2020 at 9:42 pm

    good work

    Reply
  38. ImageGulshan Aggarwal says

    October 27, 2020 at 6:19 pm

    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.

    Reply
  39. Imageurvashi says

    October 13, 2020 at 10:58 pm

    I had learnt python basics from Coursera and trust me most of the thing i saw here, wasn’t covered in coursera. Thank you 🙂

    Reply
    • ImageVishal says

      October 16, 2020 at 4:47 pm

      I am glad you liked it

      Reply
    • ImageDanilo says

      December 24, 2021 at 5:28 pm

      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.

      Reply
      • ImageVishal says

        January 2, 2022 at 11:08 am

        Thank you, Danilo.

        Reply
  40. ImageAshish says

    June 24, 2020 at 4:43 am

    SR: if you pass empty tuple, it will show Index Error

    Reply
  41. ImageShahnawaz khan says

    June 11, 2020 at 5:20 pm

    what about this code. is this correct way or wrong way for best programmer

    
    tuple1 = (44, "sd", 43, 45.55)
    tuple2 = tuple1[::-1]
    cnt = 0
    for i,j in zip(tuple1,tuple2):
        if i == j:
            c = 0
            continue
        else:
            c = 1
    
    if c == 0:
        print("Are value are same")
    else:
        print("Not All value are same")
    
    Reply
    • ImageMANAS SAMAL says

      June 17, 2021 at 9:46 pm

      Not All value are same

      Reply
      • ImageBad_Coder says

        September 8, 2021 at 8:46 pm

        n = int(input("Enter the length of the List "))
        l = []
        for i in range(n):
            l.append(int(input()))
        
        t1 = tuple(l)
        ele = t1[0]
        c=True
        for i in t1:
                if ele !=i:
                    c=False
                    break
                    
        if c==True:
            print("All of the elements of the tuple are the same")
        else:
            print("Not all of the data are same")
        Reply
        • ImageBad_Coder says

          September 8, 2021 at 8:50 pm

          n = int(input("Enter the length of the List "))
          l = []
          for i in range(n):
              l.append(int(input()))
          
          t1 = tuple(l)
          ele = t1[0]
          c = True
          for i in t1:
              if ele != i:
                  c = False
                  break
          
          if c == True:
              print("All of the elements of the tuple are the same")
          else:
              print("Not all of the data are same")
          Reply
  42. ImageDerrick says

    May 29, 2020 at 9:37 am

    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

    Reply
    • ImageVishal says

      May 31, 2020 at 11:10 am

      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="")
      
      
      Reply
  43. Imagekeerthi says

    May 28, 2020 at 9:29 pm

    WIll this work???

    tuple1 = (45, 45, 45, 45)
        if len(tuple1) == tuple1.count(45):
            return True
        else:
            return False
    
    Reply
    • ImageCharan says

      October 10, 2020 at 8:23 pm

      tuple1 = (45, 45, 45, 45)
      if len(tuple1) == tuple1.count(45):
          print("True")
      else:
          print("False")

      this is working Keerthi

      Reply
      • ImageCharan says

        October 10, 2020 at 8:27 pm

        sry, there should be indentations in those print statements

        Reply
      • ImageRishi says

        October 16, 2021 at 5:55 pm

        It is a good solution for example 10?

        tuple1 = (45, 45, 45,6)
        if tuple1.count(45)==len(tuple1):
            print(True)
        else:
            print(False)
        Reply
  44. ImageNupur says

    May 6, 2020 at 1:33 pm

    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")
    
    Reply
    • ImageVishal says

      May 7, 2020 at 8:31 pm

      Hey, Nupur, this will also work, but the solution you provided is not efficient when tuple contains more elements. Thank you

      Reply
    • ImageAshish says

      June 24, 2020 at 4:39 am

      Nupur: Wrong: Solution Try with tuple1 = (45,46,46,45)

      Reply
  45. ImageAlex says

    April 14, 2020 at 3:28 pm

    The solution (or task) in Exercise Question 10 is wrong. It will return true even if values are different:

    tuple1 = (44, "sd", 43, 45.55)
    print(all(tuple1))
    

    Output:
    True

    Reply
    • ImageVishal says

      April 15, 2020 at 12:24 am

      Alex, You are right. Now, I have updated the answer. Can you please check

      Reply
      • ImageSR says

        May 13, 2020 at 11:30 am

        Another solution:

        tuple1 = (45, 45, 45, 45)
        if len(set(tuple1)) == 1:
            print(True)
        
        Reply
        • ImageAshish says

          June 24, 2020 at 4:42 am

          SR: If you pass empty tuple, your solution will show IndexError

          Reply
          • ImageAshish says

            June 24, 2020 at 4:45 am

            Oops, I take that back. I had another issue.

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement