Count & Sort methods in tuple – Python

Count & Sort are built-in methods with tuple in Python. Tuple in Python can store duplicate & multiple datatype elements.

Follow quick-start guide, for all topics related to tuple in Python – Tuple in Python – Quickstart

Count method in tuple

Syntax of the count method:

count_value = tuple.count(object)

  • count method takes 1 object as an argument, for which we want to get the count.
  • Argument object, can be an element of any datatype or of any collection (list, tuple, set, dictionary etc.)
  • count(object) method returns the number of occurrences of given object in tuple.
  • count(object) method compares the object (element) with case-sensitivity.

There are multiple scenarios in which we can use count(element) method:

  1. Count of numeric or string element
  2. Count of case-sensitive string element
  3. Count of collection element
  4. Error – count method passed with two parameters

Count of numeric or string element

# count of numeric element
print("count of numeric element")
a = (4,2,3,4,9,4,2)                                    # tuple of numeric elements, 4 occurs three times
print(a)
print(a.count(4))                                    # count method, return count of 4 in the tuple

print("\n---------------------------------------------------\n")

# count of string element
print("count of string element")
b = ("AWS","Azure","Python","Python","Data Science","Java Advanced")
print(b)
print(b.count("Python"))                        # count method, return count of 'Python' in the tuple

For numeric tuple ‘a’, we are using count(object) method to get the count of 4, which is present 3 times in the tuple. For string tuple ‘b’, we are using count(object) method to get the count of ‘Python’, which is present 2 times in the tuple.

Program Output

count of numeric element
(4, 2, 3, 4, 9, 4, 2)
3
---------------------------------------------------
count of string element
('AWS', 'Azure', 'Python', 'Python', 'Data Science', 'Java Advanced')
2

From the program output, we got count 3 for element 4 in list and count 2 for element ‘Python’ in list.

Count of case-sensitive string element

# count of case-sensitive string element
print("count of case-sensitive string element")
shbytes_tuple = ("AWS","Azure","Python","Python","DataScience","Java Advanced")
print(shbytes_tuple)
print(shbytes_tuple.count("python"))                                  # count of case-sensitive 'python' (in small case letters)

For tuple ‘shbytes_tuple’, we are using count(object) method to get the count of ‘python’. Note – we are counting for small case letter ‘python’ but tuple contains element ‘Python’ with capital ‘P’. count(object) method will check for case-sensitivity and will return 0.

Program Output

count of case-sensitive string element
('AWS', 'Azure', 'Python', 'Python', 'DataScience', 'Java Advanced')
0

From the program output, we got count 0 for ‘python’ in tuple. But element ‘Python’ with capital ‘P’ exists 2 times.

Count of collection element in tuple

# count of collection element
print("count of collection element")

nested_tuple = (1,'Python','Azure', ['AWS',2])
print(nested_tuple)
print("count of collection - ", nested_tuple.count(['AWS',2]))        # count of collection object
print("count of empty tuple - ", nested_tuple.count(()))			# count of empty tuple

For tuple ‘nested_tuple’, we are using count(object) method to get the count of a collection ‘[‘AWS’, 2]’ and for empty tuple collection.

Program Output

count of collection element
(1, 'Python', 'Azure', ['AWS', 2])
count of collection -  1
count of empty tuple -  0

As return value, count of ‘[‘AWS’, 2]’ is 1 in the tuple and empty tuple count is 0.

Error – count method passed with two parameters

# Error when two parameters are passed
print("error when two parameters are passed")

e = ("AWS","Azure","Python","Python")
print(e)
print(e.count("Python", 2))                               # count method passed with 2 parameters

count(object) method takes only 1 parameter. If multiple parameters are passed, it will throw an error.

Program Output

error when two parameters are passed
('AWS', 'Azure', 'Python', 'Python')
Traceback (most recent call last):
  File "D:\count-element-tuple.py", line 41, in <module>
    print(e.count("Python", 2))
          ^^^^^^^^^^^^^^^^^^^^
TypeError: tuple.count() takes exactly one argument (2 given)

Sorting of tuple

Tuple is an immutable datatype and we cannot directly perform append (add), update (change) or remove (delete) operations on tuple. To do these operations on tuple, we first convert tuple into a list (mutable object) and then we perform change operations and convert list back to tuple.

In case of sorting, since sorting involves change in order (index) of elements so, we cannot perform sorting directly on tuple object. We will convert tuple into a list and then sort the list. After sorting, convert list back to tuple.

Syntax of the sort method: on list objectunsorted_list.sort(reverse)

  • sort() method is used to sort the unsorted list unsorted_list.
  • By default, sort() method sorts in Ascending order.
  • reverse (optional) – This is an optional parameter. By default its value if False. If passed as True, then sorting happens in Descending order.

Lets see sorting of numeric and string tuple with two scenarios.

  • Sort tuple in ascending order
  • Sort tuple in descending order

Sort tuple in ascending order

# sorting of alphanumeric tuple
alphanumeric_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')
print(alphanumeric_tuple)
temp_list = list(alphanumeric_tuple)          # convert tuple into a list
temp_list.sort()                                               # sorting of alphanumeric list in ascending order
alphanumeric_tuple = tuple(temp_list)      # convert sorted list into a tuple
print(alphanumeric_tuple)

# sorting of numeric tuple
numeric_tuple = (23,45,78,13, 34, 89, 67)
print(numeric_tuple)
temp_list = list(numeric_tuple)                   # convert tuple into a list
temp_list.sort()                                              # sorting of numeric list in ascending order
numeric_tuple = tuple(temp_list)                # convert sorted list into a tuple
print(numeric_tuple)

We have defined two tuples, ‘alphanumeric_tuple’ with string elements and ‘numeric_tuple’ with numeric elements. Before sorting, we are printing elements of both tuples. In both scenarios, we are first converting the tuple into a list ‘temp_list’ and then calling the sort() function on that list. After sorting, we are converting list back into a tuple.

sort() method (without reverse parameter) is called on lists to sort them in ascending order.

Program Output

('Python', 'AWS', 'Java', 'Azure', 'DataScience')
('AWS', 'Azure', 'DataScience', 'Java', 'Python')           # sorted tuple, ascending order, alphanumeric sorting

(23, 45, 78, 13, 34, 89, 67)
(13, 23, 34, 45, 67, 78, 89)                        # sorted tuple, ascending order, numeric sorting

From the output, elements of ‘alphanumeric_tuple’ are sorted in ascending order based on elements alphanumeric value. Elements of ‘numeric_tuple’ are sorted in ascending order based on elements numeric value.

Sort tuple in descending order

# sorting of alphanumeric tuple in descending order
alphanumeric_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')
print(alphanumeric_tuple)
temp_list = list(alphanumeric_tuple)                 # convert tuple into a list
temp_list.sort(reverse = True)                            # sorting of alphanumeric list in descending order
alphanumeric_tuple = tuple(temp_list)             # convert sorted list into tuple
print(alphanumeric_tuple)

# sorting of numeric tuple in descending order
numeric_tuple = (23,45,78,13, 34, 89, 67)
print(numeric_tuple)
temp_list = list(numeric_tuple)                           # convert tuple into a list
temp_list.sort(reverse = True)                            # sorting of numeric list in descending order
numeric_tuple = tuple(temp_list)                       # convert sorted list into tuple
print(numeric_tuple)

Defined two tuples, ‘alphanumeric_tuple’ with string elements and ‘numeric_tuple’ with numeric elements. Before sorting, we are printing elements of both tuples. In both scenarios, we are first converting the tuple into a list ‘temp_list’ and then calling the sort(reverse = True) function on that list. After sorting, we are converting list back into a tuple.

sort() method (with reverse = True parameter) is called on lists to sort them in descending order.

Program Output

('Python', 'AWS', 'Java', 'Azure', 'DataScience')
('Python', 'Java', 'DataScience', 'Azure', 'AWS')        # sorted list, descending order, alphanumeric sorting
(23, 45, 78, 13, 34, 89, 67)
(89, 78, 67, 45, 34, 23, 13)                                   # sorted list, descending order, numeric sorting

From the output, elements of ‘alphanumeric_tuple’ are sorted in descending order. Elements of ‘numeric_tuple’ are sorted in descending order based on elements numeric value.

Summary

In this article, we learn about count and sort method in tuple. We learned about:

Code – Github Repository

All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.

Python Topics


Interview Questions & Answers

Q: How would you sort the elements of a tuple using sorted() method?

Tuples are immutable in Python, meaning that their elements cannot be modified once the tuple is created. But we can sort the elements of a tuple by converting it to a list, sorting the list, and then converting it back to a tuple.

# Define a tuple
original_tuple = (42, 11, 31, 21, 52)

# Convert the tuple to a list
sorted_list = sorted(original_tuple)

# Convert the sorted list back to a tuple
sorted_tuple = tuple(sorted_list)

# Convert the tuple to a list and sort it in descending order
desc_sorted_list = tuple(sorted(original_tuple, reverse=True))

print(f"Original tuple: {original_tuple}")  # (42, 11, 31, 21, 52)
print(f"Sorted tuple: {sorted_tuple}")  # (11, 21, 31, 42, 52)
print(f"Descending sorted tuple: {desc_sorted_list}")  # (52, 42, 31, 21, 11)

Q: What is the time complexity of counting elements and sorting a tuple?

Counting an element – The time complexity of counting elements in a tuple using the count() method is O(n), where n is the number of elements in the tuple. This is because the method must iterate through the entire tuple to count the occurrences.

Sorting of tuple – Sorting of tuple takes three steps. The complexity of sorting of tuple involves all three steps.

  • First converting tuple into a list, whose time complexity is O(n).
  • Then sorting the list, sorted() method uses Timsort algorithm and has a time complexity of O(nlog⁡n).
  • Converting the list back to a tuple also has time complexity of O(n).
  • The overall time complexity is dominated by the sorting step, which is O(nlog⁡n).

Q: How to handle a situation where the tuple contains elements of different data types, and we need to count or sort them?

Counting – We can count elements of any type using the count() method. count() method works with any hashable datatype (integers, strings, etc.). There can be error or undefined behavior, if we try to count elements that are not comparable.

mixed_tuple = (15, 'Python', 38.78, 'Power BI', {23, 45})
count_value = mixed_tuple.count(38.78)

Sorting – Sorting a tuple containing different datatypes of elements can be tricky because Python 3 does not allow comparisons between incompatible datatypes (e.g., comparing a string with an integer). There can be two possibilities to sort such a tuple:

  1. Either ensure all elements in a tuple are of the same datatype.
  2. Either define a custom sorting key that converts all elements to a comparable form (e.g., converting all elements to strings).
# Define a tuple with mixed types
mixed_tuple = (15, 'Python', 38.78, 'Power BI')

try:
    # Attempt to sort the tuple directly
    sorted_mixed_tuple = tuple(sorted(mixed_tuple))
    print(f"Sorted mixed tuple: {sorted_mixed_tuple}")
except TypeError as e:
    print(f"Error occurred: {e}")

# Sort by converting all elements to strings
sorted_mixed_tuple = tuple(sorted(mixed_tuple, key=str))
print(f"Sorted mixed tuple as strings: {sorted_mixed_tuple}")

In this example, we have shown both scenarios. In first scenario, we are trying to sort the tuple directly without converting elements into a string. In this case, we got an error – Error occurred: '<' not supported between instances of 'str' and 'int'

In the second scenario, we are sorting the tuple by converting all elements into a string datatype using sorted(mixed_tuple, key=str). Tuple will be sorted with elements as string – (15, 38.78, 'Power BI', 'Python')

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *