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 Exercises: 30 Coding Problems with Solutions

Python Tuple Exercises: 30 Coding Problems with Solutions

Updated on: June 13, 2026 | 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.

In this article, you’ll find 32 Python tuple practice questions, sorted by difficulty. These questions cover topics like indexing, slicing, unpacking, tuple methods, data conversion, using map and filter, and working with namedtuple.

Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.

  • All solutions have been fully tested on Python 3.
  • Use our Online Code Editor to solve these exercises in real time.
  • Also, Solve Python Exercises: 29 topic-wise exercises with over 800+ coding questions

Also Read:

  • Python Tuples
  • Python Tuple Quiz: MCQs to understand Python tuple.

Let us know if you have any alternative solutions. It will help other developers.

+ Table of Contents (32 Exercises)

Table of contents

  • Exercise 1: Basic Tuple Operations
  • Exercise 2: The Trailing Comma
  • Exercise 3: Tuple Repetition
  • Exercise 4: Tuple Concatenation
  • Exercise 5: Tuple Slicing
  • Exercise 6: Tuple Reversal
  • Exercise 7: Type Casting
  • Exercise 8: Tuple to String
  • Exercise 9: Tuple Membership Testing
  • Exercise 10: Counting
  • Exercise 11: Tuple Unpacking
  • Exercise 12: The Swap Trick
  • Exercise 13: Nested Tuple Access
  • Exercise 14: Tuple Statistics
  • Exercise 22: Sort Tuple of Tuples
  • Exercise 23: Tuple Filtering
  • Exercise 24: Tuple Mapping
  • Exercise 25: Tuple Dictionary Mapping
  • Exercise 26: Tuple Intersection
  • Exercise 27: The “Modification” Hack
  • Exercise 28: Tuple Mutability
  • Exercise 29: Nested Tuple Flattening
  • Exercise 30: Memory Efficiency
  • Exercise 31: NamedTuples
  • Exercise 32: The Hashability Paradox

Exercise 1: Basic Tuple Operations

Problem Statement: Write a Python program to create a tuple, access its elements by index, and find its length.

Purpose: This exercise introduces you to the fundamental building blocks of working with tuples: creating them, retrieving individual elements using index positions, and measuring their size using len(). These are the first skills you need before working with any tuple-based data.

Given Input: fruits = ("apple", "banana", "cherry", "date")

Expected Output: First element: apple, Last element: date, and Length: 4

▼ Solution & Explanation
fruits = ("apple", "banana", "cherry", "date")

print("First element:", fruits[0])
print("Last element:", fruits[-1])
print("Length:", len(fruits))Code language: Python (python)

Explanation:

  • fruits = ("apple", "banana", "cherry", "date"): Creates a tuple by enclosing comma-separated values in parentheses. Tuples are ordered and immutable once created.
  • fruits[0]: Accesses the first element using zero-based indexing. The first item is always at index 0.
  • fruits[-1]: Uses negative indexing to access the last element. -1 always refers to the final item, regardless of the tuple’s length.
  • len(fruits): Returns the total count of elements in the tuple. Here it returns 4.

Exercise 2: The Trailing Comma

Problem Statement: Write a Python program to create a tuple containing a single item, the number 50, and confirm its type.

Purpose: This exercise highlights one of the most common beginner mistakes with tuples: assuming that parentheses alone create a tuple. A trailing comma is required when the tuple has only one element, and this exercise trains you to remember that rule.

Given Input: A single integer value 50

Expected Output: (50,) and <class 'tuple'>

▼ Solution & Explanation
t = (50,)

print(t)
print(type(t))Code language: Python (python)

Explanation:

  • t = (50,): The trailing comma after 50 is what tells Python this is a tuple, not just an integer wrapped in parentheses. Without the comma, type(t) would return <class 'int'>.
  • print(t): Displays (50,). Python always includes the trailing comma in the output of a single-element tuple to make its type visually unambiguous.
  • type(t): Confirms the variable is of type tuple. This is a useful sanity check when debugging single-item containers.

Exercise 3: Tuple Repetition

Problem Statement: Write a Python program to repeat a tuple three times using the * operator.

Purpose: This exercise shows how the * operator works with sequences. Repeating a tuple is a concise way to generate patterned data without writing loops, and it reinforces the idea that tuples support sequence operations just like strings and lists.

Given Input: colors = ("red", "green")

Expected Output: ('red', 'green', 'red', 'green', 'red', 'green')

▼ Solution & Explanation
colors = ("red", "green")

repeated = colors * 3

print(repeated)Code language: Python (python)

Explanation:

  • colors = ("red", "green"): Defines a two-element tuple to use as the base for repetition.
  • colors * 3: The * operator on sequences means repetition, not multiplication. It concatenates the tuple with itself three times, producing a new six-element tuple.
  • repeated: Stores the result. The original colors tuple is unaffected because tuples are immutable and * always produces a new object.

Exercise 4: Tuple Concatenation

Problem Statement: Write a Python program to join three separate tuples into one new tuple using the + operator.

Purpose: This exercise demonstrates how to combine multiple tuples without modifying any of the originals. Concatenation is useful when you need to assemble a final ordered collection from several independent parts.

Given Input: a = (1, 2), b = (3, 4), and c = (5, 6)

Expected Output: (1, 2, 3, 4, 5, 6)

▼ Solution & Explanation
a = (1, 2)
b = (3, 4)
c = (5, 6)

combined = a + b + c

print(combined)Code language: Python (python)

Explanation:

  • a = (1, 2), b = (3, 4), c = (5, 6): Three separate tuples, each holding two integers. None of them will be modified during this operation.
  • a + b + c: The + operator on tuples performs concatenation, joining them left to right into a single new tuple. The elements from a come first, followed by b, then c.
  • combined: Holds the resulting six-element tuple (1, 2, 3, 4, 5, 6). The originals a, b, and c remain intact.

Exercise 5: Tuple Slicing

Problem Statement: Write a Python program to extract a specific portion of a tuple using slice notation.

Purpose: This exercise teaches you how to retrieve a contiguous subset of elements from a tuple without a loop. Slicing is a fundamental Python skill used across strings, lists, and tuples alike, and it is essential for tasks like pagination, windowing, and data partitioning.

Given Input: numbers = (10, 20, 30, 40, 50, 60, 70)

Expected Output: (30, 40, 50)

▼ Solution & Explanation
numbers = (10, 20, 30, 40, 50, 60, 70)

sliced = numbers[2:5]

print(sliced)Code language: Python (python)

Explanation:

  • numbers[2:5]: Extracts elements from index 2 up to but not including index 5. This gives (30, 40, 50), which are the elements at indices 2, 3, and 4.
  • Start index (inclusive): The slice begins at index 2, which is the value 30.
  • Stop index (exclusive): The slice stops before index 5, which is the value 60. That element is not included in the result.
  • sliced: Stores the new tuple. Slicing never modifies the original tuple – it always returns a new object.

Exercise 6: Tuple Reversal

Problem Statement: Write a Python program to reverse the order of elements in a tuple.

Purpose: This exercise shows how to reverse a tuple even though tuples have no built-in .reverse() method (unlike lists). You will practice using slice notation with a step value, which is a widely used Python idiom for reversing any sequence.

Given Input: items = (1, 2, 3, 4, 5)

Expected Output: (5, 4, 3, 2, 1)

▼ Solution & Explanation
items = (1, 2, 3, 4, 5)
reversed_items = items[::-1]

print(reversed_items)Code language: Python (python)

Explanation:

  • items[::-1]: Uses extended slice notation [start:stop:step]. Omitting start and stop means the slice covers the entire tuple. The step -1 tells Python to walk backwards, producing a reversed copy.
  • reversed_items: Stores the new reversed tuple. The original items tuple is unchanged, because tuples are immutable and slicing always creates a new object.
  • Alternative: tuple(reversed(items)) achieves the same result. reversed() returns an iterator, so wrapping it in tuple() is necessary to get a tuple back. The [::-1] slice is generally preferred for its brevity.

Exercise 7: Type Casting

Problem Statement: Write a Python program to convert a list into a tuple using the tuple() constructor.

Purpose: This exercise demonstrates how to convert between mutable and immutable sequence types. Converting a list to a tuple is a common pattern when you want to protect data from accidental modification, use it as a dictionary key, or pass it to a function that expects an immutable sequence.

Given Input: my_list = [10, 20, 30, 40, 50]

Expected Output: (10, 20, 30, 40, 50) and <class 'tuple'>

▼ Solution & Explanation
my_list = [10, 20, 30, 40, 50]

my_tuple = tuple(my_list)

print(my_tuple)
print(type(my_tuple))Code language: Python (python)

Explanation:

  • my_list = [10, 20, 30, 40, 50]: A standard Python list – ordered and mutable. Lists support operations like .append() and .remove() that tuples do not.
  • tuple(my_list): The tuple() constructor accepts any iterable and returns a new tuple containing the same elements in the same order. The original list is not modified.
  • print(my_tuple): Confirms the values are preserved and now stored in a tuple: (10, 20, 30, 40, 50).
  • type(my_tuple): Returns <class 'tuple'>, confirming the conversion was successful.

Exercise 8: Tuple to String

Problem Statement: Write a Python program to convert a tuple of characters into a single joined string.

Purpose: This exercise shows how to bridge the gap between tuples and strings. The str.join() method is a core Python tool for assembling strings from iterable sequences, and practising it on a tuple reinforces that join() works on any iterable, not just lists.

Given Input: chars = ('a', 'b', 'c')

Expected Output: abc

▼ Solution & Explanation
chars = ('a', 'b', 'c')

result = "".join(chars)

print(result)Code language: Python (python)

Explanation:

  • chars = ('a', 'b', 'c'): A tuple of individual single-character strings. Each element must be a string for join() to work. Passing a tuple of integers would raise a TypeError.
  • "".join(chars): Calls join() on an empty string, which acts as the separator placed between each element. With an empty separator, the characters are concatenated directly with nothing in between.
  • result: Stores the final string "abc". The original tuple is unchanged.
  • Alternative: Using "-".join(chars) would produce "a-b-c", which is useful when you need a readable separator between items.

Exercise 9: Tuple Membership Testing

Problem Statement: Write a Python program to check whether a specific element exists inside a tuple using the in keyword.

Purpose: This exercise introduces membership testing, one of the most readable and expressive features of Python. Checking for the presence of a value in a collection is a task that appears constantly in real-world code, from input validation to search logic.

Given Input: fruits = ("apple", "banana", "cherry", "date")

Expected Output: True and False

▼ Solution & Explanation
fruits = ("apple", "banana", "cherry", "date")

print("cherry" in fruits)
print("mango" in fruits)Code language: Python (python)

Explanation:

  • "cherry" in fruits: Scans the tuple from left to right and returns True as soon as a matching element is found. Since "cherry" is present at index 2, the result is True.
  • "mango" in fruits: Scans the entire tuple and finds no match, so it returns False.
  • Performance note: The in operator on a tuple performs a linear scan, checking each element one by one. For very large collections where frequent lookups are needed, a set offers faster average-case membership testing.

Exercise 10: Counting

Problem Statement: Write a Python program to use the .count() method to find how many times a specific element appears in a tuple.

Purpose: This exercise introduces one of the two built-in methods that tuples provide. Knowing how to count occurrences without writing a manual loop is a practical skill used in frequency analysis, data validation, and duplicate detection.

Given Input: votes = ("yes", "no", "yes", "yes", "no", "yes")

Expected Output: yes appears 4 times and no appears 2 times

▼ Solution & Explanation
votes = ("yes", "no", "yes", "yes", "no", "yes")

yes_count = votes.count("yes")
no_count = votes.count("no")

print("yes appears", yes_count, "times")
print("no appears", no_count, "times")Code language: Python (python)

Explanation:

  • votes.count("yes"): Scans the entire tuple and returns the number of elements equal to "yes". The comparison is exact and case-sensitive, so "Yes" would not be counted.
  • votes.count("no"): Repeats the scan for "no", returning 2. Each call to .count() is a separate linear scan of the tuple.
  • Context: Tuples have only two built-in methods: .count() and .index(). This is intentional – tuples are designed to be lightweight and immutable, so they expose far fewer methods than lists.

Exercise 11: Tuple Unpacking

Problem Statement: Write a Python program to unpack a four-element tuple into four distinct variables in a single assignment.

Purpose: This exercise introduces tuple unpacking, one of Python’s most elegant features. Unpacking makes code more readable by giving meaningful names to positional data, and it is widely used when working with function return values, database rows, and coordinate pairs.

Given Input: person = ("Alice", 30, "Engineer", "Pune")

Expected Output: Name: Alice, Age: 30, Job: Engineer, and City: Pune

▼ Solution & Explanation
person = ("Alice", 30, "Engineer", "Pune")

name, age, job, city = person

print("Name:", name)
print("Age:", age)
print("Job:", job)
print("City:", city)Code language: Python (python)

Explanation:

  • name, age, job, city = person: Python matches each variable on the left to the corresponding element in the tuple by position. name gets "Alice", age gets 30, job gets "Engineer", and city gets "Pune".
  • Count must match: If the number of variables does not equal the number of tuple elements, Python raises ValueError: too many values to unpack or ValueError: not enough values to unpack.
  • Alternative: If you only need some values, use an underscore _ as a throwaway variable for positions you want to skip, e.g., name, _, job, _ = person.

Exercise 12: The Swap Trick

Problem Statement: Write a Python program to swap the values of two variables using tuple unpacking, without using a temporary third variable.

Purpose: This exercise demonstrates one of Python’s most well-known idioms. The swap trick works because Python evaluates the entire right-hand side as a tuple before performing any assignment, making it both concise and safe. It is a practical showcase of how unpacking can replace verbose boilerplate code.

Given Input: a = 100 and b = 200

Expected Output: After swap: a = 200, b = 100

▼ Solution & Explanation
a = 100
b = 200

a, b = b, a

print("After swap: a =", a, ", b =", b)Code language: Python (python)

Explanation:

  • a, b = b, a: Python first evaluates the right-hand side b, a as a whole, creating the temporary tuple (200, 100). It then unpacks that tuple into a and b from left to right, assigning 200 to a and 100 to b.
  • Why no temp variable is needed: The right-hand side is fully evaluated before any assignment takes place. This means the original values of both a and b are captured in the temporary tuple before either variable is overwritten.
  • Classic alternative: In most other languages, swapping requires a third variable: temp = a; a = b; b = temp. Python’s tuple unpacking makes this unnecessary and is considered the idiomatic approach.

Exercise 13: Nested Tuple Access

Problem Statement: Write a Python program to access a specific element that is stored inside a tuple which is itself nested inside another tuple.

Purpose: This exercise builds your understanding of nested data structures. Tuples can contain other tuples as elements, and chaining index operators is the standard way to drill down into them. This pattern appears frequently when working with coordinate grids, database records, and configuration structures.

Given Input: matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

Expected Output: 6

▼ Solution & Explanation
matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))

element = matrix[1][2]

print(element)Code language: Python (python)

Explanation:

  • matrix[1]: Accesses the element at index 1 of the outer tuple, which is the inner tuple (4, 5, 6).
  • matrix[1][2]: Chains a second index onto the result. This accesses index 2 of the inner tuple (4, 5, 6), which is the value 6.
  • General pattern: For any level of nesting, you chain one additional index operator per level. A triple-nested tuple would require three index operators: data[i][j][k].
  • Immutability note: Even inside a nested structure, you cannot reassign any element. An attempt like matrix[1][2] = 99 raises a TypeError because tuples do not support item assignment at any level.

Exercise 14: Tuple Statistics

Problem Statement: Write a Python program to calculate the total, highest value, and lowest value from a tuple of integers using the built-in sum(), max(), and min() functions.

Purpose: This exercise shows that Python’s built-in aggregate functions work directly on tuples, not just lists. Being able to derive quick statistics from an immutable sequence without converting it first is a practical time-saver in data processing and reporting tasks.

Given Input: scores = (88, 95, 70, 62, 99, 74, 85)

Expected Output: Sum: 573, Max: 99, and Min: 62

▼ Solution & Explanation
scores = (88, 95, 70, 62, 99, 74, 85)

total = sum(scores)
highest = max(scores)
lowest = min(scores)

print("Sum:", total)
print("Max:", highest)
print("Min:", lowest)Code language: Python (python)

Explanation:

  • sum(scores): Iterates over the tuple and adds all elements together, returning the total 573. It accepts an optional second argument as a starting value, e.g., sum(scores, 100) would return 673.
  • max(scores): Scans the tuple and returns the largest value. For numeric tuples, it compares by arithmetic value. For string tuples, it would compare lexicographically.
  • min(scores): Scans the tuple and returns the smallest value, in this case 62. Like max(), it raises a ValueError if the tuple is empty.
  • Combining results: You can derive the average by combining sum() and len(): sum(scores) / len(scores) gives 81.857..., extending this exercise naturally into a statistics summary.

Exercise 22: Sort Tuple of Tuples

Problem Statement: Write a Python program to sort a tuple of tuples based on the second item in each nested tuple.

Purpose: This exercise teaches you how to use the key parameter of Python’s sorted() function with a lambda to sort structured data by a specific field – a technique used constantly when ordering records, rankings, and tabular data.

Given Input: students = (("Alice", 88), ("Bob", 73), ("Charlie", 95), ("Diana", 61))

Expected Output:

Sorted: (('Diana', 61), ('Bob', 73), ('Alice', 88), ('Charlie', 95))
▼ Solution & Explanation
students = (("Alice", 88), ("Bob", 73), ("Charlie", 95), ("Diana", 61))

sorted_students = tuple(sorted(students, key=lambda x: x[1]))
print("Sorted:", sorted_students)Code language: Python (python)

Explanation:

  • sorted(students, key=lambda x: x[1]): The key parameter accepts a callable that is applied to each element before comparison. Here, lambda x: x[1] extracts the second item of every nested tuple as the sort criterion.
  • lambda x: x[1]: A compact anonymous function that takes one argument x (a nested tuple) and returns its element at index 1. This avoids importing operator.itemgetter for a simple one-off sort.
  • tuple(...): sorted() always returns a list. Wrapping the result in tuple() restores the immutable tuple type to match the original data structure.

Exercise 23: Tuple Filtering

Problem Statement: Write a Python program to filter a tuple and keep only the elements that satisfy a given condition, using both filter() and a list comprehension approach.

Purpose: This exercise demonstrates two idiomatic ways to select a subset of items from a sequence based on a condition. Filtering is a foundational operation in data processing, validation, and functional-style programming.

Given Input: numbers = (3, 14, 7, 22, 9, 41, 18, 5), keep only values greater than 10

Expected Output: Filtered: (14, 22, 41, 18)

▼ Solution & Explanation
numbers = (3, 14, 7, 22, 9, 41, 18, 5)

# Using filter()
filtered_filter = tuple(filter(lambda x: x > 10, numbers))
print("Using filter():", filtered_filter)

# Using a generator expression
filtered_comp = tuple(x for x in numbers if x > 10)
print("Using comprehension:", filtered_comp)Code language: Python (python)

Explanation:

  • filter(lambda x: x > 10, numbers): Applies the lambda to every element and keeps only those for which it returns True. filter() returns a lazy iterator, so tuple() is needed to materialise the result.
  • tuple(x for x in numbers if x > 10): A generator expression with an inline if condition. This is the more Pythonic style and is easier to read when the condition grows more complex.
  • Order is preserved: Both approaches iterate through numbers from left to right, so qualifying elements appear in their original sequence in the output.

Exercise 24: Tuple Mapping

Problem Statement: Write a Python program to apply a square function to every item in a tuple using map(), and also demonstrate the equivalent generator expression approach.

Purpose: This exercise introduces the functional programming concept of mapping a transformation over a sequence. The map() function and its comprehension equivalent appear regularly in data transformation, preprocessing pipelines, and mathematical computations.

Given Input: numbers = (1, 2, 3, 4, 5, 6)

Expected Output: Squared: (1, 4, 9, 16, 25, 36)

▼ Solution & Explanation
numbers = (1, 2, 3, 4, 5, 6)

def square(n):
    return n * n

# Using map()
squared_map = tuple(map(square, numbers))
print("Using map():", squared_map)

# Using a generator expression
squared_comp = tuple(x ** 2 for x in numbers)
print("Using comprehension:", squared_comp)Code language: Python (python)

Explanation:

  • map(square, numbers): Applies square to each element of numbers one at a time and returns a lazy map iterator. Wrapping it in tuple() forces evaluation and collects all results.
  • def square(n): A named function is used here instead of a lambda to keep the code readable and to make the intent self-documenting. For a one-liner, map(lambda x: x * x, numbers) works identically.
  • x ** 2: The exponentiation operator is a clear and concise alternative to x * x. In the generator expression, it makes the transformation immediately obvious without needing a separate function definition.

Exercise 25: Tuple Dictionary Mapping

Problem Statement: Write a Python program to zip two tuples together – one holding keys and the other holding values – to create a dictionary.

Purpose: This exercise demonstrates a common pattern for building dictionaries from paired data sources. Combining zip() with dict() is widely used when parsing CSV headers, mapping configuration keys to values, and constructing lookup tables from separate lists.

Given Input: keys = ("name", "age", "city") and values = ("Alice", 30, "Pune")

Expected Output: {'name': 'Alice', 'age': 30, 'city': 'Pune'}

▼ Solution & Explanation
keys = ("name", "age", "city")
values = ("Alice", 30, "Pune")

mapping = dict(zip(keys, values))
print(mapping)

# Alternative: dictionary comprehension
mapping_comp = {k: v for k, v in zip(keys, values)}
print(mapping_comp)Code language: Python (python)

Explanation:

  • zip(keys, values): Pairs elements from both tuples by position, producing a lazy iterator of two-item tuples: ('name', 'Alice'), ('age', 30), and so on.
  • dict(...): Consumes the zipped iterator and interprets each two-item tuple as a key-value pair, building the final dictionary in a single call with no explicit loop needed.
  • {k: v for k, v in zip(keys, values)}: The dictionary comprehension equivalent. It is slightly more verbose but gives you room to add conditions or transform keys and values inline during construction.

Exercise 26: Tuple Intersection

Problem Statement: Write a Python program to find all elements that are common to two different tuples.

Purpose: This exercise introduces set intersection as a tool for comparing collections. Finding shared elements between two sequences is a core operation in data analysis, deduplication, access control (shared permissions), and any scenario where you need to identify overlap between datasets.

Given Input: t1 = (1, 2, 3, 4, 5, 6) and t2 = (4, 5, 6, 7, 8, 9)

Expected Output: Common elements: (4, 5, 6)

▼ Solution & Explanation
t1 = (1, 2, 3, 4, 5, 6)
t2 = (4, 5, 6, 7, 8, 9)

# Using set intersection
common = tuple(sorted(set(t1) & set(t2)))
print("Common elements:", common)

# Alternative: generator expression (order-preserving)
common_ordered = tuple(x for x in t1 if x in set(t2))
print("Common elements (ordered):", common_ordered)Code language: Python (python)

Explanation:

  • set(t1) & set(t2): Converts both tuples to sets and applies the & intersection operator, which returns a new set containing only the values present in both. This is an O(min(n, m)) operation, making it efficient for large inputs.
  • tuple(sorted(...)): Since set intersection produces an unordered result, sorted() ensures the output is in ascending order before it is converted back to a tuple.
  • x for x in t1 if x in set(t2): The generator expression approach converts t2 to a set once for O(1) membership checks, then iterates through t1 in order. This preserves the original sequence of t1 while still benefiting from fast set lookups.

Exercise 27: The “Modification” Hack

Problem Statement: Write a Python program to “modify” a tuple by converting it to a list, changing a specific item, and converting it back to a tuple.

Purpose: This exercise highlights the immutability of tuples and demonstrates the standard workaround used when a one-off change is needed. Understanding this pattern also helps you appreciate why tuples are immutable by design and when to choose a list instead.

Given Input: colours = ("red", "green", "blue"), replace "green" with "yellow"

Expected Output:

Original: ('red', 'green', 'blue')
Modified: ('red', 'yellow', 'blue')
▼ Solution & Explanation
colours = ("red", "green", "blue")
print("Original:", colours)

temp = list(colours)
temp[1] = "yellow"
colours_modified = tuple(temp)

print("Modified:", colours_modified)Code language: Python (python)

Explanation:

  • list(colours): Creates a brand-new mutable list containing the same elements as the tuple. The original tuple is not touched at any point in this process.
  • temp[1] = "yellow": Performs the desired in-place change on the list. This would raise a TypeError if attempted directly on the tuple, because tuples do not support item assignment.
  • tuple(temp): Converts the modified list back into a new immutable tuple. The result is a separate object in memory; the variable colours still points to the original, unmodified tuple.

Exercise 28: Tuple Mutability

Problem Statement: Create a tuple that contains a list as one of its elements. Modify the list in place and observe that the tuple’s identity stays the same while its contents appear to change.

Purpose: This exercise uncovers one of Python’s most instructive subtleties: a tuple is immutable in the sense that its references cannot be reassigned, but if a reference points to a mutable object such as a list, that object itself can still be changed. Understanding this distinction is essential for writing predictable, bug-free code.

Given Input: t = (1, 2, [3, 4, 5]), append 99 to the inner list

Expected Output:

Before: (1, 2, [3, 4, 5])
After: (1, 2, [3, 4, 5, 99])
Same object? True
▼ Solution & Explanation
t = (1, 2, [3, 4, 5])
print("Before:", t)
print("Tuple id before:", id(t))

t[2].append(99)

print("After: ", t)
print("Tuple id after: ", id(t))
print("Same object?", id(t) == id(t))Code language: Python (python)

Explanation:

  • t[2].append(99): t[2] retrieves the reference to the list stored at index 2. Calling .append() mutates that list object in place. The tuple’s slot at index 2 still holds the exact same reference; only the list’s contents have grown.
  • id(t): Returns the unique memory address of the tuple object. Printing it before and after confirms the tuple itself is the same object in memory – its identity has not changed, even though its printed representation looks different.
  • The immutability rule clarified: Tuple immutability means the tuple’s references cannot be rebound. You cannot do t[2] = something_else. But the object that a reference points to can change freely if that object is mutable – which is exactly what a list is.

Exercise 29: Nested Tuple Flattening

Problem Statement: Write a recursive Python function to flatten a deeply nested tuple of tuples into a single flat tuple containing all the individual values.

Purpose: This exercise strengthens your understanding of recursion and type checking. Flattening nested structures is a practical requirement when processing tree-shaped data, parsed expressions, or hierarchical configurations where depth is not known in advance.

Given Input: nested = (1, (2, 3), (4, (5, (6, 7))))

Expected Output: Flattened: (1, 2, 3, 4, 5, 6, 7)

▼ Solution & Explanation
def flatten(t):
    for item in t:
        if isinstance(item, tuple):
            yield from flatten(item)
        else:
            yield item

nested = (1, (2, 3), (4, (5, (6, 7))))
result = tuple(flatten(nested))
print("Flattened:", result)Code language: Python (python)

Explanation:

  • isinstance(item, tuple): The base condition that separates recursive cases from base cases. If the current item is itself a tuple, the function dives into it; otherwise, the item is a plain value and is yielded directly to the caller.
  • yield from flatten(item): Delegates iteration to the recursive call, forwarding every value it produces upward through the call stack. This avoids manually looping over the sub-results and keeps the function body concise.
  • tuple(flatten(nested)): Since flatten is a generator function, calling it returns a lazy iterator. Passing that iterator to tuple() forces full evaluation and collects every yielded value into the final flat tuple.

Exercise 30: Memory Efficiency

Problem Statement: Use the sys module to measure and compare the memory consumed by a list and a tuple, each holding the same one million integer elements.

Purpose: This exercise gives you concrete, measurable evidence for one of the key practical advantages of tuples over lists: lower memory overhead. This matters in performance-sensitive applications that hold large collections of fixed data in memory.

Given Input: A range of one million integers, range(1_000_000), stored as both a list and a tuple

Expected Output: Printed byte sizes for the list and the tuple, followed by the difference in bytes (exact values vary by Python version and platform)

▼ Solution & Explanation
import sys

data = range(1_000_000)
large_list  = list(data)
large_tuple = tuple(data)

list_size  = sys.getsizeof(large_list)
tuple_size = sys.getsizeof(large_tuple)
difference = list_size - tuple_size

print(f"List size:  {list_size:,} bytes")
print(f"Tuple size: {tuple_size:,} bytes")
print(f"Difference: {difference:,} bytes ({difference / 1024:.2f} KB)")Code language: Python (python)

Explanation:

  • sys.getsizeof(): Returns the memory footprint of the container object itself in bytes. For a list, this includes extra capacity reserved for future appends (over-allocation). A tuple allocates exactly as much space as it needs and no more.
  • Over-allocation in lists: Python lists maintain a buffer of spare slots to make .append() efficient. This means a list nearly always occupies more memory than a tuple of the same length, because the tuple has no need to grow and carries no such buffer.
  • Shallow vs. deep size: sys.getsizeof() measures only the container, not the objects it references. Both the list and the tuple point to the same integer objects in memory, so the element memory is identical for both. The difference shown is purely the container overhead.

Exercise 31: NamedTuples

Problem Statement: Use collections.namedtuple to define an Employee data structure with named fields, create a few instances, and perform a calculation such as finding the highest-paid employee.

Purpose: This exercise introduces namedtuple as a lightweight way to create readable, self-documenting data objects without the overhead of a full class. Named tuples are used extensively in standard library code, data pipelines, and anywhere structured records need to be passed around efficiently.

Given Input: Three employees – ("Alice", "Engineering", 95000), ("Bob", "Marketing", 72000), ("Charlie", "Engineering", 88000)

Expected Output:

Alice works in Engineering and earns $95,000
Bob works in Marketing and earns $72,000
Charlie works in Engineering and earns $88,000
Highest paid: Alice ($95,000)
▼ Solution & Explanation
from collections import namedtuple

Employee = namedtuple("Employee", ["name", "department", "salary"])

employees = (
    Employee("Alice",   "Engineering", 95000),
    Employee("Bob",     "Marketing",   72000),
    Employee("Charlie", "Engineering", 88000),
)

for emp in employees:
    print(f"{emp.name} works in {emp.department} and earns ${emp.salary:,}")

top = max(employees, key=lambda e: e.salary)
print(f"Highest paid: {top.name} (${top.salary:,})")Code language: Python (python)

Explanation:

  • namedtuple("Employee", [...]): Dynamically creates a new tuple subclass called Employee whose fields can be accessed by name. The result behaves exactly like a regular tuple for indexing, unpacking, and memory usage, but adds attribute-style access for clarity.
  • emp.name, emp.department, emp.salary: Named field access makes the code self-documenting. Compare this to a plain tuple where emp[0], emp[1], emp[2] would give no indication of what each position represents.
  • max(employees, key=lambda e: e.salary): Finds the Employee instance with the highest salary value. Because named tuples are still tuples, they work seamlessly with all built-in functions like max(), min(), and sorted().

Exercise 32: The Hashability Paradox

Problem Statement: Write a Python program that experiments with using tuples as dictionary keys. Demonstrate why a fully immutable tuple like (1, 2) works as a key, while a tuple containing a mutable object like (1, [2]) raises a TypeError.

Purpose: This exercise builds a deep understanding of Python’s hashing rules. Dictionary keys must be hashable, meaning their value must never change after being inserted. A tuple containing a mutable list violates this guarantee, which is why Python rejects it. This concept is fundamental to understanding how sets and dictionaries work internally.

Given Input: Attempt to use (1, 2) and (1, [2]) as dictionary keys

Expected Output:

(1, 2) as key: success, value = "immutable tuple"
(1, [2]) as key: TypeError - unhashable type: 'list'
▼ Solution & Explanation
d = {}

# Fully immutable tuple: works as a key
try:
    d[(1, 2)] = "immutable tuple"
    print(f"(1, 2) as key: success, value = \"{d[(1, 2)]}\"")
except TypeError as e:
    print(f"(1, 2) as key: TypeError - {e}")

# Tuple containing a list: raises TypeError
try:
    d[(1, [2])] = "tuple with list"
    print(f"(1, [2]) as key: success, value = \"{d[(1, [2])]}\"")
except TypeError as e:
    print(f"(1, [2]) as key: TypeError - {e}")

# Demonstrating hash() directly
print("\nhash((1, 2))  =", hash((1, 2)))
try:
    print("hash((1, [2])) =", hash((1, [2])))
except TypeError as e:
    print(f"hash((1, [2])): TypeError - {e}")Code language: Python (python)

Explanation:

  • Hashability requirement: Python dictionaries and sets store keys by their hash value. For this to work correctly, a key’s hash must remain constant for its entire lifetime in the container. Objects whose value can change – such as lists – are deliberately made unhashable to prevent silent data corruption.
  • Why (1, 2) is hashable: Both elements are integers, which are immutable. A tuple is hashable if and only if every element it contains is also hashable. Python computes the tuple’s hash from the hashes of its elements, so a fully immutable tuple produces a stable, reliable hash value.
  • Why (1, [2]) is not hashable: The list [2] inside the tuple is mutable. If it were allowed as a dictionary key and then modified, the hash would change, making the key unretrievable. Python prevents this entirely by raising a TypeError at the moment you attempt to hash any tuple that contains a mutable element, however deeply nested.

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有

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

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. harry 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. Sachin 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. Sayi says

    November 29, 2023 at 6:53 pm

    Another answer for number 10 , may be

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

    Reply
    • Idrees 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. fateme says

    November 18, 2023 at 10:06 am

    Q 10. Another solution:

    tuple1 = (45, 45, 45, 45)

    print(all(tuple1))

    Reply
    • Sayi says

      November 29, 2023 at 6:53 pm

      Same answer as mine

      Reply
    • Ajay 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
      • SOUMYA 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. Amir 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
    • dhia 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
      • Scott hollland says

        April 13, 2024 at 3:53 pm

        Super it works for me.

        Reply
      • Deepak says

        June 4, 2024 at 11:49 pm

        what if we have 100 or 1000 values?

        Reply
    • romankrv says

      December 8, 2023 at 5:48 pm

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

      Reply
    • Okbazghi says

      February 2, 2025 at 12:37 am

      Great idea!

      Reply
    • Abhi 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. MohammadHO3ein Hahsemi says

    August 24, 2023 at 12:04 pm

    thank you so much, that was very helpful

    Reply
  7. Matla 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. Matla 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
    • Emilio 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
      • Matla Avinash says

        May 10, 2023 at 7:18 pm

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

        Reply
        • romankrv 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
    • AIyman says

      June 15, 2023 at 1:11 pm

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

      Reply
    • Nanu 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
    • Sr1kanth says

      October 20, 2024 at 3:17 pm

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

      Reply
  9. Matla 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
    • Emilio 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
      • Matla Avinash says

        May 10, 2023 at 7:09 pm

        Thank you

        Reply
  10. vini1955 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. Khan says

    November 4, 2022 at 7:56 am

    pls guide how to use to comment a code?

    Reply
    • Akash 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. Khan 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. TuanNG 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
    • TuanNG says

      October 27, 2022 at 8:11 pm

      Make sure we have a comma after i in for loop

      Reply
    • A 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. SR 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
    • Sravani says

      February 2, 2023 at 6:00 pm

      Above program why we use -1

      Reply
      • Shahzad 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
    • Muhammad 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. SR 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. Bhuvi Sakthi says

    September 4, 2022 at 9:59 am

    is this correct??

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

    True

    Reply
    • Thangavel says

      September 12, 2022 at 10:56 pm

      tuple1 = (45, 45, 45, 45)
      result=  tuple1 == tuple1
      print(result)
      Reply
      • Thangavel 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. David 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
    • Bob says

      September 2, 2022 at 2:55 pm

      agreed. I took the same approach.

      Reply
  18. Domey_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. Nassim 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. Serkan 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
    • Ivan says

      September 29, 2022 at 11:23 pm

      Nice one!

      Reply
  21. rayhon 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
    • bob 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. Abdou 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
    • Akash 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. Abdou 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. Abdou 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. Rishikesh 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
    • TuanNG 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. DIvya says

    March 6, 2022 at 3:04 pm

    What does lambda x: x[1] mean?

    Reply
    • Praful 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. Josh 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. Bernard 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
    • Jacob 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. Majid 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
    • Ritik 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. Ganesh 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
    • Gilfoyle 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
      • Gilfoyle says

        October 26, 2021 at 3:09 pm

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

        Reply
  31. HARIHARAN 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. Filipe 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
    • Aakash 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. ashaar 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
    • Vishal says

      March 9, 2021 at 8:08 pm

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

      Reply
  34. Marton 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
    • Vishal says

      March 2, 2021 at 8:53 pm

      Thank you, Marton.

      Reply
  35. Nick 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. Luis 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
    • Danilo 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. patience says

    December 24, 2020 at 9:42 pm

    good work

    Reply
  38. Gulshan 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. urvashi 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
    • Vishal says

      October 16, 2020 at 4:47 pm

      I am glad you liked it

      Reply
    • Danilo 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
      • Vishal says

        January 2, 2022 at 11:08 am

        Thank you, Danilo.

        Reply
  40. Ashish says

    June 24, 2020 at 4:43 am

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

    Reply
  41. Shahnawaz 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
    • MANAS SAMAL says

      June 17, 2021 at 9:46 pm

      Not All value are same

      Reply
      • Bad_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
        • Bad_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. Derrick 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
    • Vishal 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. keerthi 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
    • Charan 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
      • Charan says

        October 10, 2020 at 8:27 pm

        sry, there should be indentations in those print statements

        Reply
      • Rishi 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. Nupur 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
    • Vishal 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
    • Ashish says

      June 24, 2020 at 4:39 am

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

      Reply
  45. Alex 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
    • Vishal says

      April 15, 2020 at 12:24 am

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

      Reply
      • SR says

        May 13, 2020 at 11:30 am

        Another solution:

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

          June 24, 2020 at 4:42 am

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

          Reply
          • Ashish 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 Exercises for Beginners
  • Loop Exercises
  • Intermediate Python Exercises
  • Input and Output Exercises
  • Functions Exercises
  • String Exercises
  • List Exercises
  • Dictionary Exercises
  • Set Exercises
  • Tuple Exercises
  • Data Structure Exercises
  • Comprehensions Exercises
  • Collections Module Exercises
  • Date and Time Exercises
  • OOP Exercises
  • Exception Handling Exercises
  • Math and Statistics Exercises
  • File Handling Exercises
  • OS and Sys Module Exercises
  • Regex Exercises
  • Lambda & Functional Programming Exercises
  • Iterators & Generators Exercises
  • Itertools & Functools Exercises
  • Random Data Generation Exercises
  • NumPy Exercises
  • Pandas Exercises
  • Matplotlib Exercises
  • Python Database Exercises
  • Python JSON Exercises

 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

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有