Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Python Tuples

A collection of ordered and immutable objects
("Python", "tuples", "immutable", "object")
(23, 42, 12, 53, 64)
Creating a Tuple ()
Creating a tuple having objects of different data types
nested tuple
("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
create a tuple without using parentheses
4, 5.7, "Tuples", ["Python", "Tuples"]
access element index more than the length of a tuple
Accessing the index of a nested tuple
nested_tuple[0][3]
Using slicing to access elements of the tuple==tuple_[1:3]
Printing the entire tuple by using the default start and end values==tuple_[:]
Repetition Tuples in Python==tuple_ * 3

Python Tuples

A collection of ordered and immutable objects is known as a tuple. Tuples and lists are similar as they both are sequences. Though, tuples and lists are different because we cannot modify tuples, although we can modify lists after creating them, and also because we use parentheses to create tuples while we use square brackets to create lists.

Placing different values separated by commas and enclosed in parentheses forms a tuple. For instance,

Example

tuple_1 = ("Python", "tuples", "immutable", "object")  
tuple_2 = (23, 42, 12, 53, 64)  
tuple_3 = "Python", "Tuples", "Ordered", "Collection"  
Enter fullscreen mode Exit fullscreen mode

We represent an empty tuple by two parentheses enclosing nothing.

Empty_tuple = ()  
Enter fullscreen mode Exit fullscreen mode

We need to add a comma after the element to create a tuple of a single element.

Tuple_1 = (50,)

Creating a Tuple
All the objects (elements) must be enclosed in parenthesis (), each separated by a comma, to form a tuple. Although using parenthesis is not required, it is recommended to do so.

Whatever the number of objects, even of various data types, can be included in a tuple (dictionary, string, float, list, etc.).

Python program to show how to create a tuple

Creating an empty tuple

empty_tuple = ()  
print("Empty tuple: ", empty_tuple)  
Enter fullscreen mode Exit fullscreen mode

Creating tuple having integers

int_tuple = (4, 6, 8, 10, 12, 14)  
print("Tuple with integers: ", int_tuple) 
Enter fullscreen mode Exit fullscreen mode

Creating a tuple having objects of different data types

mixed_tuple = (4, "Python", 9.3)  
print("Tuple with different data types: ", mixed_tuple)  
Enter fullscreen mode Exit fullscreen mode

Creating a nested tuple

nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))  
print("A nested tuple: ", nested_tuple)  
Enter fullscreen mode Exit fullscreen mode

Output:

Empty tuple:  ()
Tuple with integers:  (4, 6, 8, 10, 12, 14)
Tuple with different data types:  (4, 'Python', 9.3)
A nested tuple:  ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Enter fullscreen mode Exit fullscreen mode

Python program to create a tuple without using parentheses

Creating a tuple

tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]  
Enter fullscreen mode Exit fullscreen mode

displaying the tuple created

print(tuple_)  
Enter fullscreen mode Exit fullscreen mode

Checking the data type of object tuple_

print( type(tuple_) )

trying to modify tuple_

try:  
    tuple_[1] = 4.2  
except:  
    print( TypeError )  
Enter fullscreen mode Exit fullscreen mode

Output:

(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>
Enter fullscreen mode Exit fullscreen mode

Python program to show how to access tuple elements

Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Collection")  

print(tuple_[0])    
print(tuple_[1]) 
Enter fullscreen mode Exit fullscreen mode

trying to access element index more than the length of a tuple

 print(tuple_[5]) 
Enter fullscreen mode Exit fullscreen mode

except Exception as e:

print(e)

trying to access elements through the index of floating data type

try:

print(tuple_[1.0])

except Exception as e:

print(e)

Creating a nested tuple

nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))  
Enter fullscreen mode Exit fullscreen mode

Accessing the index of a nested tuple

print(nested_tuple[0][3])         
print(nested_tuple[1][1])  
Enter fullscreen mode Exit fullscreen mode

Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
Enter fullscreen mode Exit fullscreen mode

Python program to show how slicing works in Python tuples

Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects") 
Enter fullscreen mode Exit fullscreen mode

Using slicing to access elements of the tuple

print("Elements between indices 1 and 3: ", tuple_[1:3]) 
Enter fullscreen mode Exit fullscreen mode

Using negative indexing in slicing

print("Elements between indices 0 and -4: ", tuple_[:-4])  
Enter fullscreen mode Exit fullscreen mode

Printing the entire tuple by using the default start and end values.

print("Entire tuple: ", tuple_[:])  
Enter fullscreen mode Exit fullscreen mode

Output:

Elements between indices 1 and 3:  ('Tuple', 'Ordered')
Elements between indices 0 and -4:  ('Python', 'Tuple')
Entire tuple:  ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')
Enter fullscreen mode Exit fullscreen mode

Repetition Tuples in Python

** Python program to show repetition in tuples **

tuple_ = ('Python',"Tuples")  
print("Original tuple is: ", tuple_)  

 Repeting the tuple elements  
tuple_ = tuple_ * 3  
print("New tuple is: ", tuple_)  
Enter fullscreen mode Exit fullscreen mode

Output:

Original tuple is:  ('Python', 'Tuples')
New tuple is:  ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Enter fullscreen mode Exit fullscreen mode

Tuple Methods
Tuple does not provide methods to add or delete elements, and there are only the following two choices.

Examples of these methods are given below.

Python program to show how to tuple methods (.index() and .count()) work

Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered") 
Enter fullscreen mode Exit fullscreen mode

Counting the occurrence of an element of the tuple using the count() method

print(tuple_.count('Ordered'))  
Enter fullscreen mode Exit fullscreen mode

Getting the index of an element using the index() method

print(tuple_.index('Ordered')) # This method returns index of the first occurrence of the element

Output:

2
2

Tuple Membership Test
Using the in keyword, we can determine whether an item is present in the given tuple or not.

Python program to show how to perform membership test for tuples

Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")  

In operator  
print('Tuple' in tuple_)  
print('Items' in tuple_)  

 Not in operator  
print('Immutable' not in tuple_)  
print('Items' not in tuple_)  
Enter fullscreen mode Exit fullscreen mode

Output:

True
False
False
True
Iterating Through a Tuple
We can use a for loop to iterate through each element of a tuple.
Enter fullscreen mode Exit fullscreen mode

Code

Python program to show how to iterate over tuple elements

Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable")  

 Iterating over tuple elements using a for loop  
for item in tuple_:  
    print(item)  
Enter fullscreen mode Exit fullscreen mode

Output:

Python
Tuple
Ordered
Immutable
Changing a Tuple
Tuples, as opposed to lists, are immutable objects.
Enter fullscreen mode Exit fullscreen mode

This implies that after a tuple's elements have been specified, we cannot modify them. However, we can modify the nested elements of an element if the element itself is a mutable data type like a list.

A tuple can be assigned to many values (reassignment).

Python program to show that Python tuples are immutable objects

Creating a tuple

tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])

Trying to change the element at index 2

try:

tuple_[2] = "Items"

print(tuple_)

except Exception as e:

print( e )

But inside a tuple, we can change elements of a mutable object

tuple_[-1][2] = 10

print(tuple_)

Changing the whole tuple

tuple_ = ("Python", "Items")

print(tuple_)

Output:

'tuple' object does not support item assignment

('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')
Enter fullscreen mode Exit fullscreen mode

Code

Python program to show how to concatenate tuples

 Creating a tuple  
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")  

Adding a tuple to the tuple_  
print(tuple_ + (4, 5, 6))  
Enter fullscreen mode Exit fullscreen mode

Output:

('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)
Enter fullscreen mode Exit fullscreen mode

Advantages of Tuple over List
Tuples and lists are employed in similar contexts because of how similar they are. A tuple implementation has several benefits over a list, though. The following are a few of the primary benefits:

We generally employ lists for homogeneous data types and tuples for heterogeneous data types.
Tuple iteration is quicker than list iteration because tuples are immutable. There is such a modest performance improvement.
Tuples with immutable components can function as the key for a Python dictionary object. This feature is not feasible with lists.
Collecting data in a tuple will ensure that it stays write-protected if it never changes.

==========================================================

Tuple Question

  1. Create an empty tuple and add integers 1 to 5 to it.
  2. Access the third element of a tuple containing names.
  3. Given a tuple of numbers, calculate the sum of all the elements.
  4. Create a tuple of fruits and check if a specific fruit is present.
  5. Iterate through a tuple of words and print each word in uppercase.
  6. Concatenate two tuples to create a new tuple.
  7. Given a tuple of numbers, find the maximum and minimum values.
  8. Write a function to convert a tuple to a list.
  9. Find the index of a specific element in a tuple.
  10. Create a tuple of strings and sort them in alphabetical order.
  11. Count the occurrences of a specific element in a tuple.
  12. Check if a given tuple is a palindrome.
  13. Write a function to reverse a tuple.
  14. Create a tuple of numbers and filter out the even numbers.
  15. Write a function to find the product of elements in a tuple of numbers.
  16. Given a tuple of words, create a new tuple with the lengths of the words.
  17. Find the second largest element in a tuple of numbers.
  18. Create a tuple of strings and capitalize the first letter of each string.
  19. Write a function to merge two tuples into one, preserving the order.
  20. Calculate the average of elements in a tuple of numbers.
  21. Check if all elements in a tuple are greater than a specified value.
  22. Write a function to find the intersection of two tuples.
  23. Create a tuple of integers and find the sum and product of its elements.
  24. Remove duplicate elements from a tuple.
  25. Given two tuples of numbers, find the common elements between them.
  26. Create a nested tuple and access its inner elements.
  27. Convert a tuple of strings into a single string by joining them.
  28. Create a tuple of mixed data types and find the count of integers and strings.
  29. Write a function to rotate the elements of a tuple to the right by a specified number of positions.
  30. Given a tuple of coordinates (x, y), calculate the distance from the origin for each point.
  31. These questions cover various aspects of working with tuples in Python . =============================================================
# Task 1: Create an empty tuple and add integers 1 to 5 to it.
empty_tuple = ()
filled_tuple = empty_tuple + (1, 2, 3, 4, 5)
print("Task 1 - Tuple with Integers 1 to 5:", filled_tuple)

# Task 2: Access the third element of a tuple containing names.
names_tuple = ("Alice", "Bob", "Charlie", "David", "Eve")
third_name = names_tuple[2]
print("Task 2 - Third Element of Names Tuple:", third_name)

# Task 3: Given a tuple of numbers, calculate the sum of all the elements.
numbers_tuple = (10, 20, 30, 40, 50)
sum_of_elements = sum(numbers_tuple)
print("Task 3 - Sum of Elements in Numbers Tuple:", sum_of_elements)

# Task 4: Create a tuple of fruits and check if a specific fruit is present.
fruits_tuple = ("apple", "banana", "cherry", "date", "elderberry")
specific_fruit = "banana"
is_present = specific_fruit in fruits_tuple
print("Task 4 - Is '{}' Present in Fruits Tuple: {}".format(specific_fruit, is_present))

# Task 5: Iterate through a tuple of words and print each word in uppercase.
words_tuple = ("hello", "world", "python", "tuple")
for word in words_tuple:
    print("Task 5 - Uppercase Word:", word.upper())

# Task 6: Concatenate two tuples to create a new tuple.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print("Task 6 - Concatenated Tuple:", concatenated_tuple)

# Task 7: Given a tuple of numbers, find the maximum and minimum values.
numbers_tuple = (15, 30, 10, 45, 20)
max_value = max(numbers_tuple)
min_value = min(numbers_tuple)
print("Task 7 - Max Value:", max_value)
print("Task 7 - Min Value:", min_value)

# Task 8: Write a function to convert a tuple to a list.
def tuple_to_list(input_tuple):
    return list(input_tuple)

tuple_to_convert = (1, 2, 3, 4, 5)
converted_list = tuple_to_list(tuple_to_convert)
print("Task 8 - Converted List:", converted_list)

# Task 9: Find the index of a specific element in a tuple.
fruits_tuple = ("apple", "banana", "cherry", "date", "elderberry")
element_to_find = "date"
index_of_element = fruits_tuple.index(element_to_find)
print("Task 9 - Index of '{}' in Fruits Tuple: {}".format(element_to_find, index_of_element))

# Task 10: Create a tuple of strings and sort them in alphabetical order.
strings_tuple = ("zebra", "apple", "cherry", "banana", "date")
sorted_tuple = tuple(sorted(strings_tuple))
print("Task 10 - Sorted Tuple:", sorted_tuple)

# Task 11: Count the occurrences of a specific element in a tuple.
numbers_tuple = (1, 2, 2, 3, 2, 4, 2, 5)
element_to_count = 2
count_of_element = numbers_tuple.count(element_to_count)
print("Task 11 - Count of '{}' in Numbers Tuple: {}".format(element_to_count, count_of_element))

# Task 12: Check if a given tuple is a palindrome.
def is_palindrome(input_tuple):
    return input_tuple == input_tuple[::-1]

palindrome_tuple = (1, 2, 3, 2, 1)
is_palindrome_result = is_palindrome(palindrome_tuple)
print("Task 12 - Is Tuple a Palindrome:", is_palindrome_result)

# Task 13: Write a function to reverse a tuple.
def reverse_tuple(input_tuple):
    return input_tuple[::-1]

tuple_to_reverse = (5, 4, 3, 2, 1)
reversed_tuple = reverse_tuple(tuple_to_reverse)
print("Task 13 - Reversed Tuple:", reversed_tuple)

# Task 14: Create a tuple of numbers and filter out the even numbers.
numbers_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
filtered_tuple = tuple(filter(lambda x: x % 2 != 0, numbers_tuple))
print("Task 14 - Filtered Tuple (Odd Numbers Only):", filtered_tuple)

# Task 15: Write a function to find the product of elements in a tuple of numbers.
def product_of_elements(input_tuple):
    result = 1
    for element in input_tuple:
        result *= element
    return result

numbers_to_multiply = (2, 3, 4, 5)
product = product_of_elements(numbers_to_multiply)
print("Task 15 - Product of Elements in Tuple:", product)
Enter fullscreen mode Exit fullscreen mode

Output

Task 1 - Tuple with Integers 1 to 5: (1, 2, 3, 4, 5)
Task 2 - Third Element of Names Tuple: Charlie
Task 3 - Sum of Elements in Numbers Tuple: 150
Task 4 - Is 'banana' Present in Fruits Tuple: True
Task 5 - Uppercase Word: HELLO
Task 5 - Uppercase Word: WORLD
Task 5 - Uppercase Word: PYTHON
Task 5 - Uppercase Word: TUPLE
Task 6 - Concatenated Tuple: (1, 2, 3, 4, 5, 6)
Task 7 - Max Value: 45
Task 7 - Min Value: 10
Task 8 - Converted List: [1, 2, 3, 4, 5]
Task 9 - Index of 'date' in Fruits Tuple: 3
Task 10 - Sorted Tuple: ('apple', 'banana', 'cherry', 'date', 'zebra')
Task 11 - Count of '2' in Numbers Tuple: 4
Task 12 - Is Tuple a Palindrome: True
Task 13 - Reversed Tuple: (1, 2, 3, 4, 5)
Task 14 - Filtered Tuple (Odd Numbers Only): (1, 3, 5, 7, 9)
Task 15 - Product of Elements in Tuple: 120
Enter fullscreen mode Exit fullscreen mode
# Task 16: Given a tuple of words, create a new tuple with the lengths of the words.
words_tuple = ("apple", "banana", "cherry", "date", "elderberry")
word_lengths = tuple(len(word) for word in words_tuple)
print("Task 16 - Word Lengths Tuple:", word_lengths)

# Task 17: Find the second largest element in a tuple of numbers.
numbers_tuple = (10, 20, 30, 40, 50)
sorted_numbers = sorted(numbers_tuple)
second_largest = sorted_numbers[-2]
print("Task 17 - Second Largest Element:", second_largest)

# Task 18: Create a tuple of strings and capitalize the first letter of each string.
strings_tuple = ("apple", "banana", "cherry", "date", "elderberry")
capitalized_strings = tuple(word.capitalize() for word in strings_tuple)
print("Task 18 - Capitalized Strings Tuple:", capitalized_strings)

# Task 19: Write a function to merge two tuples into one, preserving the order.
def merge_tuples(tuple1, tuple2):
    return tuple1 + tuple2

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
merged_tuple = merge_tuples(tuple1, tuple2)
print("Task 19 - Merged Tuple:", merged_tuple)

# Task 20: Calculate the average of elements in a tuple of numbers.
numbers_tuple = (10, 20, 30, 40, 50)
average = sum(numbers_tuple) / len(numbers_tuple)
print("Task 20 - Average:", average)

# Task 21: Check if all elements in a tuple are greater than a specified value.
numbers_tuple = (10, 20, 30, 40, 50)
specified_value = 15
all_greater = all(element > specified_value for element in numbers_tuple)
print("Task 21 - All Elements Greater Than {}: {}".format(specified_value, all_greater))

# Task 22: Write a function to find the intersection of two tuples.
def tuple_intersection(tuple1, tuple2):
    return tuple(set(tuple1) & set(tuple2))

tuple1 = (1, 2, 3, 4, 5)
tuple2 = (4, 5, 6, 7, 8)
intersection_result = tuple_intersection(tuple1, tuple2)
print("Task 22 - Intersection of Tuples:", intersection_result)

# Task 23: Create a tuple of integers and find the sum and product of its elements.
integers_tuple = (1, 2, 3, 4, 5)
sum_of_elements = sum(integers_tuple)
product_of_elements = 1
for element in integers_tuple:
    product_of_elements *= element
print("Task 23 - Sum of Elements:", sum_of_elements)
print("Task 23 - Product of Elements:", product_of_elements)

# Task 24: Remove duplicate elements from a tuple.
original_tuple = (1, 2, 2, 3, 4, 4, 5)
unique_tuple = tuple(set(original_tuple))
print("Task 24 - Unique Tuple:", unique_tuple)

# Task 25: Given two tuples of numbers, find the common elements between them.
tuple1 = (1, 2, 3, 4, 5)
tuple2 = (4, 5, 6, 7, 8)
common_elements = tuple(element for element in tuple1 if element in tuple2)
print("Task 25 - Common Elements:", common_elements)

# Task 26: Create a nested tuple and access its inner elements.
nested_tuple = ((1, 2), (3, 4), (5, 6))
inner_element = nested_tuple[1][0]
print("Task 26 - Inner Element:", inner_element)

# Task 27: Convert a tuple of strings into a single string by joining them.
strings_tuple = ("apple", "banana", "cherry")
joined_string = ', '.join(strings_tuple)
print("Task 27 - Joined String:", joined_string)

# Task 28: Create a tuple of mixed data types and find the count of integers and strings.
mixed_tuple = (1, "apple", 2, "banana", 3, "cherry")
count_integers = sum(1 for element in mixed_tuple if isinstance(element, int))
count_strings = sum(1 for element in mixed_tuple if isinstance(element, str))
print("Task 28 - Count of Integers:", count_integers)
print("Task 28 - Count of Strings:", count_strings)

# Task 29: Write a function to rotate the elements of a tuple to the right by a specified number of positions.
def rotate_tuple_right(input_tuple, positions):
    positions = positions % len(input_tuple)
    return input_tuple[-positions:] + input_tuple[:-positions]

tuple_to_rotate = (1, 2, 3, 4, 5)
rotated_tuple = rotate_tuple_right(tuple_to_rotate, 2)
print("Task 29 - Rotated Tuple:", rotated_tuple)

# Task 30: Given a tuple of coordinates (x, y), calculate the distance from the origin for each point.
import math

coordinates_tuple = ((3, 4), (0, 0), (1, 1), (-2, 2))
distances = tuple(math.sqrt(x**2 + y**2) for x, y in coordinates_tuple)
print("Task 30 - Distances from Origin:", distances)
Enter fullscreen mode Exit fullscreen mode

OUTPUT
Good question with tuple===== .

Check if a given tuple is a palindrome.

write a function to find the product of elements in a tuple of numbers.
Given a tuple of words, create a new tuple with the lengths of the words.
Find the second largest element in a tuple of numbers..

Top comments (0)