Intensity Coding
  • HOME
  • TUTORIALS
    • Python
    • Natural Language Processing
  • ABOUT US
    • About Us
    • Contact Us
    • Privacy Policy
    • Terms and Conditions
    • Disclaimer

Python

Python Tuples

Python
Python
  • Introduction To Python
  • Write Your First Python Program
  • Indentation And Comments in Python
  • Variables in Python
  • Data Types in Python
  • Booleans and Number in Python
  • Operators in Python
  • Mutable Vs Immutable Objects And Collection in Python
  • Python String
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Control Statements
  • Python Functions
  • Python Lambda Functions
  • Python Regular Expressions (RegEx)
  • Python JSON

IC_Python_Tutorial-11_Python_Tuples.png

Python Tuples¶

Introduction of Tuples¶

  • A tuple is a collection used to store multiple elements in a single variable.
  • Tuple elements are ordered, immutable, and support duplicate values.
  • Each item in a tuple has an index, starting from [0] for the first element, [1] for the second, and so on.
  • Tuples cannot be modified once created, meaning elements cannot be changed, added, or removed.
  • Tuples are defined using round brackets ().
  • The len() function is used to find the number of elements in a tuple.
In [ ]:
# Defining a tuple with duplicate elements
intensity_levels = ("high", "medium", "low", "high", "low")

# Display the tuple
print(intensity_levels)

# Finding the number of elements in the tuple
print(len(intensity_levels))  # Output: 5
('high', 'medium', 'low', 'high', 'low')
5

Checking Tuple Type¶

  • In Python, tuples are internally recognized as objects of type tuple.
  • Use the type() function to verify if a variable is a tuple.
In [ ]:
# Define a tuple
mytuple = ("Intensity", "Coding", "Python")

# Check the type of the tuple
print(type(mytuple))
# Output: <class 'tuple'>
<class 'tuple'>

Tuples with Different Data Types¶

    • A tuple can store elements of various data types, including strings, integers, and boolean values.
In [ ]:
# Tuple with string values
tuple1 = ("extreme", "moderate", "mild")

# Tuple with integer values
tuple2 = (100, 75, 50, 25, 10)

# Tuple with boolean values
tuple3 = (True, False, False)

# Tuple with mixed data types
tuple4 = ("critical", 90, True, 60, "normal")

print(tuple1)  # Output: ('extreme', 'moderate', 'mild')
print(tuple2)  # Output: (100, 75, 50, 25, 10)
print(tuple3)  # Output: (True, False, False)
print(tuple4)  # Output: ('critical', 90, True, 60, 'normal')
('extreme', 'moderate', 'mild')
(100, 75, 50, 25, 10)
(True, False, False)
('critical', 90, True, 60, 'normal')

Creating a Tuple with One Element¶

  • To define a single-item tuple, a comma (,) must be added after the item.
  • Without the comma, Python will treat it as a regular data type instead of a tuple.
In [ ]:
# Correct way to create a one-element tuple
single_tuple = ("urgent",)
print(type(single_tuple))  # Output: <class 'tuple'>

# Incorrect way (not a tuple)
not_a_tuple = ("urgent")
print(type(not_a_tuple))  # Output: <class 'str'>
<class 'tuple'>
<class 'str'>

Using the tuple() Constructor¶

  • Tuples can also be created using the tuple() constructor.
In [ ]:
# Creating a tuple using the tuple() function
intensity_tuple = tuple(("critical", "warning", "normal"))
print(intensity_tuple)  # Output: ('critical', 'warning', 'normal')
('critical', 'warning', 'normal')

Finding the Maximum Value in a Tuple¶

  • The max() function returns the element with the highest value in the tuple.

Syntax:¶

max(tuple)

Parameters:¶

  • tuple: The tuple from which the maximum value is retrieved.

Returns:¶

  • The element with the highest value.
In [ ]:
# Defining tuples with intensity levels
intensity_str = ("low", "medium", "high", "critical")
intensity_numeric = (10, 50, 90, 100)

# Finding the maximum value
print("Max intensity (string):", max(intensity_str))  # Output: 'medium' (based on alphabetical order)
print("Max intensity (numeric):", max(intensity_numeric))  # Output: 100
Max intensity (string): medium
Max intensity (numeric): 100

Finding the Minimum Value in a Tuple¶

  • The min() function returns the element with the lowest value in the tuple.

Syntax:¶

min(tuple)

Parameters:¶

  • tuple: The tuple from which the minimum value is retrieved.

Returns:¶

  • The element with the lowest value.
In [ ]:
# Defining tuples with intensity levels
intensity_str = ("low", "medium", "high", "critical")
intensity_numeric = (10, 50, 90, 100)

# Finding the minimum value
print("Min intensity (string):", min(intensity_str))  # Output: 'critical' (based on alphabetical order)
print("Min intensity (numeric):", min(intensity_numeric))  # Output: 10
Min intensity (string): critical
Min intensity (numeric): 10

Accessing Tuple Items¶

  • Tuple elements are accessed using index numbers.

  • Indexing starts at 0 for the first item.

  • Negative indexing allows access from the end, where -1 refers to the last element, -2 to the second last, and so on.

In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "critical")

# Accessing elements using positive and negative indexing
print(intensity_levels[1])   # Output: medium
print(intensity_levels[-1])  # Output: critical
medium
critical

Slicing Tuples (Range of Indexes)¶

  • Tuples support slicing, allowing extraction of a subset of elements.
  • Syntax: tuple[start:end]
    • The start index is included.
    • The end index is excluded.
  • Omitting the start index begins the slice from the first element.
  • Omitting the end index extends the slice to the last element.
  • Negative slicing allows selection from the end.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "moderate", "high", "critical", "extreme", "severe", "intensity coding")

# Extracting elements within a range
print(intensity_levels[2:5])   # Output: ('high', 'critical', 'extreme')

# Extracting from the start to index 4
print(intensity_levels[:4])    # Output: ('low', 'moderate', 'high', 'critical')

# Extracting from index 2 to the end
print(intensity_levels[2:])    # Output: ('high', 'critical', 'extreme', 'severe', 'intensity coding')

# Extracting using negative indexes
print(intensity_levels[-4:-1]) # Output: ('critical', 'extreme', 'severe')
('high', 'critical', 'extreme')
('low', 'moderate', 'high', 'critical')
('high', 'critical', 'extreme', 'severe', 'intensity coding')
('critical', 'extreme', 'severe')

Tuple Operations: Repetition and Concatenation¶

  • Tuples can be repeated using * and concatenated using +.
In [ ]:
# Defining tuples
tuple1 = ("intensity coding", 100, "high", 75, "medium")
tuple2 = (50, "low")

# Repeating a tuple
print(tuple1 * 2)  # Output: ('intensity coding', 100, 'high', 75, 'medium', 'intensity coding', 100, 'high', 75, 'medium')

# Concatenating tuples
print(tuple1 + tuple2)  # Output: ('intensity coding', 100, 'high', 75, 'medium', 50, 'low')
('intensity coding', 100, 'high', 75, 'medium', 'intensity coding', 100, 'high', 75, 'medium')
('intensity coding', 100, 'high', 75, 'medium', 50, 'low')

Checking for Element Existence in a Tuple¶

  • Use the in keyword to check if an item exists in a tuple.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "moderate", "high", "critical", "intensity coding")

# Checking if an element exists
if "intensity coding" in intensity_levels:
    print("Yes, 'intensity coding' is in the tuple")  # Output: Yes, 'intensity coding' is in the tuple
Yes, 'intensity coding' is in the tuple

Updating Tuples¶

Modifying Tuple Values¶

  • Tuples are immutable, meaning once created, their values cannot be changed, added, or removed.
  • However, a workaround is to convert the tuple into a list, modify it, and convert it back into a tuple.
In [ ]:
# Original tuple
intensity_levels = ("low", "medium", "high")

# Converting tuple to list
temp_list = list(intensity_levels)

# Modifying an element
temp_list[1] = "critical"

# Converting back to tuple
intensity_levels = tuple(temp_list)

print(intensity_levels)  # Output: ('low', 'critical', 'high')
('low', 'critical', 'high')

Adding Items to a Tuple¶

  • Since tuples are immutable, they do not support methods like append(). However, you can add elements by:
  1. Converting the tuple into a list, adding an item, and converting it back.
  2. Concatenating two tuples.
In [ ]:
# Method 1: Convert tuple to list, then add item
intensity_levels = ("low", "medium", "high")
temp_list = list(intensity_levels)
temp_list.append("intensity coding")
intensity_levels = tuple(temp_list)

print(intensity_levels)  # Output: ('low', 'medium', 'high', 'intensity coding')

# Method 2: Adding a new tuple to an existing tuple
intensity_levels = ("low", "medium", "high")
new_tuple = ("intensity coding",)
intensity_levels += new_tuple  # Concatenation

print(intensity_levels)  # Output: ('low', 'medium', 'high', 'intensity coding')
('low', 'medium', 'high', 'intensity coding')
('low', 'medium', 'high', 'intensity coding')

Removing Items from a Tuple¶

  • Tuples do not support item removal directly because they are immutable.
  • The workaround is to convert the tuple into a list, remove the item, and convert it back.
  • You can also delete the entire tuple using del.
In [ ]:
# Removing an item using a list conversion
intensity_levels = ("low", "medium", "high", "intensity coding")
temp_list = list(intensity_levels)
temp_list.remove("medium")
intensity_levels = tuple(temp_list)

print(intensity_levels)  # Output: ('low', 'high', 'intensity coding')

# Deleting an entire tuple
intensity_levels = ("low", "medium", "high")
del intensity_levels

# print(intensity_levels)  # This will raise an error since the tuple no longer exists
('low', 'high', 'intensity coding')

Unpacking Tuples¶

Packing and Unpacking Tuples¶

  • Packing refers to assigning multiple values to a tuple.

  • Unpacking extracts values from a tuple into separate variables.

  • The number of variables must match the number of elements in the tuple.

  • If the number of variables is less than the number of values, use an asterisk (*) to store remaining values as a list.

In [ ]:
# Packing a tuple
intensity_levels = ("low", "medium", "high")

# Unpacking a tuple into variables
(low, moderate, high) = intensity_levels

print(low)       # Output: low
print(moderate)  # Output: medium
print(high)      # Output: high
low
medium
high

Using Asterisk (*) in Unpacking¶

  • If there are more values than variables, the * operator collects extra values as a list.
  • If the * is added before a variable other than the last one, Python distributes values accordingly.

Storing Remaining Values in a List¶

In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "critical", "intensity coding")

# Using * to collect remaining values
(low, moderate, *high_intensity) = intensity_levels

print(low)            # Output: low
print(moderate)       # Output: medium
print(high_intensity) # Output: ['high', 'critical', 'intensity coding']
low
medium
['high', 'critical', 'intensity coding']

Using * in the Middle of Unpacking¶

In [ ]:
# Defining a tuple
intensity_levels = ("low", "moderate", "high", "critical", "intensity coding")

# Placing * in the middle
(low, *moderate_levels, high) = intensity_levels

print(low)              # Output: low
print(moderate_levels)  # Output: ['moderate', 'high', 'critical']
print(high)             # Output: intensity coding
low
['moderate', 'high', 'critical']
intensity coding

Looping Through Tuples¶

Using a For Loop¶

  • You can iterate through a tuple using a for loop.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "critical", "intensity coding")

# Iterating through the tuple
for level in intensity_levels:
    print(level)

# Output:
# low
# medium
# high
# critical
# intensity coding
low
medium
high
critical
intensity coding

Looping Through Tuple Indexes¶

  • You can loop through the index numbers using range(len(tuple)).
In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "critical")

# Looping through indexes
for i in range(len(intensity_levels)):
    print(intensity_levels[i])

# Output:
# low
# medium
# high
# critical
low
medium
high
critical

Using a While Loop¶

  • A while loop can also be used to iterate through tuples.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "intensity coding")

# Initializing index
i = 0

# Iterating with while loop
while i < len(intensity_levels):
    print(intensity_levels[i])
    i += 1

# Output:
# low
# medium
# high
# intensity coding
low
medium
high
intensity coding

Using List Comprehension¶

  • List comprehension can be used to loop through tuples in a single line.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "intensity coding")

# Using list comprehension
[print(level) for level in intensity_levels]

# Output:
# low
# medium
# high
# intensity coding
low
medium
high
intensity coding
Out[ ]:
[None, None, None, None]

Joining and Multiplying Tuples¶

Joining Tuples¶

  • You can concatenate two or more tuples using the + operator.
In [ ]:
# Defining two tuples
intensity_levels = ("low", "medium", "high")
extra_levels = ("critical", "intensity coding")

# Joining tuples
all_levels = intensity_levels + extra_levels

print(all_levels)
# Output: ('low', 'medium', 'high', 'critical', 'intensity coding')
('low', 'medium', 'high', 'critical', 'intensity coding')

Multiplying Tuples¶

  • If you want to repeat the contents of a tuple multiple times, use the * operator.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high")

# Multiplying the tuple
repeated_levels = intensity_levels * 2

print(repeated_levels)
# Output: ('low', 'medium', 'high', 'low', 'medium', 'high')
('low', 'medium', 'high', 'low', 'medium', 'high')

Basic Tuple Operations¶

Python Expression Results Description
len((1, 2, 3)) 3 Length of tuple
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('intensity coding',) * 3 ('intensity coding', 'intensity coding', 'intensity coding') Repetition
3 in (1, 2, 3, 4, 5) True Membership check
for x in (1, 2, 3): print(x, end=" ") 1 2 3 Iteration
In [ ]:
# Length of a tuple
intensity_levels = ("low", "medium", "high")
print(len(intensity_levels))  # Output: 3

# Concatenation of tuples
extra_levels = ("critical", "intensity coding")
all_levels = intensity_levels + extra_levels
print(all_levels)  # Output: ('low', 'medium', 'high', 'critical', 'intensity coding')

# Repetition of elements
repeated_tuple = ("intensity coding",) * 3
print(repeated_tuple)
# Output: ('intensity coding', 'intensity coding', 'intensity coding')

# Membership check
print("medium" in intensity_levels)  # Output: True

# Iteration through a tuple
for level in intensity_levels:
    print(level, end=" ")  # Output: low medium high
3
('low', 'medium', 'high', 'critical', 'intensity coding')
('intensity coding', 'intensity coding', 'intensity coding')
True
low medium high 

Python - Tuple Methods¶

Tuple methods in python¶

No Method Description
1 count() Returns the number of times a specified value appears in a tuple.
2 index() Searches for a specified value and returns its position (index).

1. count()¶

Point Description

Use Case | The count() method returns the number of times a specified value appears in a tuple. |
Syntax | tuple.count(value) |
Parameter | value (Required) — The element whose occurrences need to be counted in the tuple. |


Useful Information¶

No. Point Description
1 Works Only on Tuples The method is specific to tuple objects and cannot be used with other data structures.
2 Case-Sensitive For string elements, the method considers uppercase and lowercase as different values.
3 Returns 0 if Not Found If the specified value is not present in the tuple, it returns 0.
4 Does Not Modify Tuple The method only returns a count; it does not change the original tuple.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "critical", "high", "intensity coding", "high")

# Counting occurrences of "high"
high_count = intensity_levels.count("high")

print(high_count)
# Output: 3
3

2. index()¶

Point Description

Use Case | The index() method finds the first occurrence of a specified value in a tuple. |
Syntax | tuple.index(value) |
Parameter | value (Required) — The element to search for in the tuple. |


Useful Information¶

No. Point Description
1 Returns First Occurrence If a value appears multiple times, it returns the index of its first occurrence.
2 Raises an Error if Not Found If the specified value is not in the tuple, Python raises a ValueError.
3 Indexing Starts at 0 The first item in a tuple has an index of 0.
4 Can Be Used with Different Data Types Works with numbers, strings, and other data types in tuples.
In [ ]:
# Defining a tuple
intensity_levels = ("low", "medium", "high", "critical", "high", "intensity coding", "high")

# Finding the index of "high"
high_index = intensity_levels.index("high")

print(high_index)
# Output: 2 (first occurrence of "high")
2
Category
Python Natural Language Processing
Tag's
Python Natural Language Processing

Quick Links

  • Home
  • Tutorials
  • About Us
  • Contact Us

Tutorials

  • Python
  • Natural Language Processing

Tag's

  • Python
  • Natural Language Processing

About Intensity Coding

  • Intensity Coding is your learning hub for Data Science, Machine Learning, Deep Learning, NLP, and Generative AI. From beginner to expert level, we offer clear tutorials, real-world examples, and up-to-date insights. Our content simplifies complex topics to help you grow in your AI journey.
Intensity Coding

© 2025 Intensity Coding. All Rights Reserved.

Privacy Policy Terms and Conditions Disclaimer