The count()
& Sort()
methods are built-in methods in Python lists, useful for counting occurrences of elements and sorting of elements in the list. Lists in Python can store duplicate elements and elements of various data types, making these methods essential for data handling.
In previous article, we learned about Loops and List Comprehension in Python. In this article we will learn about Python Count Method & Python Sort Methods.
Python Count Method in List
The count()
method is used to determine how many times a specific object appears in a list. Syntax of the count()
method => count_value = list.count(object)
- The
count()
method takes a single object as an argument and returns the number of occurrences of that object in the list. - Argument object, can be an element of any datatype or of any collection (list, tuple, set, dictionary etc.)
- It compares the elements with case sensitivity, so make sure to pass the exact value you are counting.
There are multiple scenarios in which we can use count(object)
method:
- Count of Numeric or String Element
- Count of Case-Sensitive String Element
- Count of Collection Element
- Error: Count Method Passed with Two Parameters
Count of Numeric or String Element
The count()
method can be used to count the occurrences of numeric or string elements in a list.
# Count of Numeric or String Element
print ("count of numeric element")
a = [4, 2, 3, 4, 9, 4, 2] # list of numeric elements, 4 occurs three times
print(a)
print("count of 4 in list - ", a.count(4)) # count method, return count of 4 in the list
print("\n---------------------------------------------------\n")
# count of string element
print("count of string element") # list of string elements
b = ["AWS", "Azure", "Python", "Python", "Data Science", "Java Advanced"]
print(b)
print("count of 'Python' in list - ", b.count("Python")) # count method, return count of 'Python' in the list
In this example program we have used the count() method with list of numeric elements and a list of string elements. For numeric list a
, we are using a.count(4)
method to get the count of 4
, which is present 3 times in the list. For string list b
, we are using b.count("Python")
method to get the count of Python
, which is present 2 times in the list.
Output – Example Program – Count of Numeric or String Element
count of numeric element
[4, 2, 3, 4, 9, 4, 2]
count of 4 in list - 3
---------------------------------------------------
count of string element
['AWS', 'Azure', 'Python', 'Python', 'Data Science', 'Java Advanced']
count of 'Python' in list - 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
The count()
method is case-sensitive. For example, counting Python
will not count python
.
# Count of Case-Sensitive String Element
print("count of case-sensitive string element")
string_list = ["AWS", "Azure", "Python", "Python", "Data Science", "Java Advanced"]
print(string_list)
print("count of case-sensitive 'python' in list - ", string_list.count("python")) # count of case-sensitive 'python'
In this example program, we have defined string_list
of string elements. We are using string_list.count("python")
method to get the count of python
. Note – we are counting for small case letter python
but list contains element Python
with capital P
. count(
method will compare elements with case-sensitivity and 0 occurrences of "python"
)python
will be found.
Output – Example Program – Count of Case-Sensitive String Element
count of case-sensitive string element
['AWS', 'Azure', 'Python', 'Python', 'Data Science', 'Java Advanced']
0 # No occurrences of small letter python in the list
From the program output, we got count 0 for python
in the list. But element Python
with capital ‘P’ exists 2 times.
Count of Collection Element
The count()
method can also count collection elements within a list.
# Count of Collection Element
print("count of collection element")
nested_list = [1, 'Python', 'Azure', ['AWS',2]]
print(nested_list)
print(nested_list.count(['AWS',2])) # count of collection element
print(nested_list.count([])) # count of empty list
In this example program, we have defined a nested_list
. We are using nested_list.count(['AWS',2])
method to get the count of a collection element ['AWS',2]
and nested_list.count([])
to get the count of empty list.
Output – Example Program – Count of Collection Element
count of collection element
[1, 'Python', 'Azure', ['AWS', 2]]
1 # occurrence of ['AWS', 2] in the list
0 # occurrence of [] in the list
As return value from this program, count of ['AWS', 2]
in the list is 1 and empty list count is 0.
Error: Count Method Passed with Two Parameters
The count()
method accepts only one argument. If multiple parameters are passed, it will raise an error.
# Error: Count Method Passed with Two Parameters
print("Error - count method passed with two parameters")
e = ["AWS","Azure","Python","Python"]
print(e)
print(e.count("Python", 2)) # count method passed with 2 parameters
Output – Example Program – Error: Count Method Passed with Two Parameters
Error - count method passed with two parameters
['AWS', 'Azure', 'Python', 'Python']
Traceback (most recent call last):
File "D:-count-element-list.py", line 41, in <module>
print(e.count("Python", 2))
^^^^^^^^^^^^^^^^^^^^
TypeError: list.count() takes exactly one argument (2 given)
Python Sort Method in List
The sort()
method is used to sort the list in Python, either in ascending or descending order. Syntax of the sort method => unsorted_list.sort(reverse)
- By default,
sort()
method sorts in ascending order. reverse
(optional) – This is an optional parameter. By default its value ifFalse
. If passed asTrue
, then sorting happens in descending order.
Lets see sorting of numeric and string list with two scenarios.
- Python Sort Method – List Sorting in Ascending Order
- Python Sort Method – List Sorting in Descending Order
Python Sort Method – List Sorting in Ascending Order
Sorting a list in ascending order can be done using the sort()
method without the reverse
parameter.
# sorting of alphanumeric list in ascending order
alphanumeric_list = ['Python', 'AWS', 'Java', 'Azure', 'DataScience']
print(alphanumeric_list)
alphanumeric_list.sort() # sorting of alphanumeric list in ascending order
print(alphanumeric_list)
# sorting of numeric list in ascending order
numeric_list = [23,45,78,13, 34, 89, 67]
print(numeric_list)
numeric_list.sort() # sorting of numeric list in ascending order
print(numeric_list)
In this example program, we have defined two lists – alphanumeric_list
with string elements and numeric_list
with numeric elements. Elements of both the lists are printed before sorting. sort()
method (without reverse
parameter) is called on both lists to sort them in ascending order.
alphanumeric_list.sort()
=> This will sort thealphanumeric_list
in ascending order based on the alphanumeric characters.numeric_list.sort()
=> This will sort thenumeric_list
in ascending order based on the numeric values.
Output – Example Program – List Sorting in Ascending Order
['Python', 'AWS', 'Java', 'Azure', 'DataScience']
['AWS', 'Azure', 'DataScience', 'Java', 'Python'] # alphanumeric sorting - sorted list in ascending order
[23, 45, 78, 13, 34, 89, 67]
[13, 23, 34, 45, 67, 78, 89] # numeric sorting - sorted list, ascending order
From the program output, elements of alphanumeric_list
are sorted in ascending order based on elements alphanumeric value. Elements of numeric_list
are sorted in ascending order based on elements numeric value.
Python Sort Method – List Sorting in Descending Order
# sorting of alphanumeric list in descending order
alphanumeric_list = ['Python', 'AWS', 'Java', 'Azure', 'DataScience']
print(alphanumeric_list)
alphanumeric_list.sort(reverse = True) # sorting of alphanumeric list in descending order
print(alphanumeric_list)
# sorting of numeric list in descending order
numeric_list = [23,45,78,13, 34, 89, 67]
print(numeric_list)
numeric_list.sort(reverse = True) # sorting of numeric list in descending order
print(numeric_list)
In this example program, we have defined two lists – alphanumeric_list
with string elements and numeric_list
with numeric elements. Elements of both the lists are printed before sorting. sort(reverse = True)
method (with reverse = True
parameter) is called on both lists to sort them in descending order.
alphanumeric_list.sort(reverse = True)
=> This will sort thealphanumeric_list
in descending order based on the alphanumeric characters.numeric_list.sort(reverse = True)
=> This will sort thenumeric_list
in descending order based on the numeric values.
Output – Example Program – List Sorting in Descending Order
['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 program output, elements of alphanumeric_list
are sorted in descending order based on elements alphanumeric value. Elements of numeric_list
are sorted in descending order based on elements numeric value.
Summary
In this article, we explored the use of the count()
and sort()
methods in Python lists. Here’s a quick recap:
- Python Count Method in List
- Count of Numeric or String Element
- Count of Case-Sensitive String Element
- Count of Collection Element
- Error: Count Method Passed with Two Parameters
- Python Sort Method in List
- Python Sort Method – List Sorting in Ascending Order
- Python Sort Method – List Sorting in Descending Order
By understanding these methods, you can efficiently manipulate and manage lists in Python.
Code snippets and programs related to Count & Sort Methods in Python Lists, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
count()
method?
Q: What is the time complexity of The time complexity of the count()
method is O(n), where n is the number of elements in the list. This is because the method needs to traverse the entire list (iterate over all the elements of the list) to count the occurrences of the specified element.
Q: How can we count the occurrences of multiple elements in a list?
We can use a loop or a dictionary comprehension to count multiple elements in a list.
elements_to_count = [22, 32, 22, 22, 52, 32]
counts = {element: elements_to_count.count(element) for element in elements_to_count}
print(counts) # count of elements: {22: 3, 32: 2, 52: 1}
sort()
method?
Q: What is the time complexity of the The time complexity of the sort()
method is O(n log n) where n is the number of elements in the list. Python’s sort implementation uses Timsort (data sorting algorithm), which is highly efficient for real data.
sort()
and sorted()
in Python?
Q: What is the difference between sort()
method modifies the original list and returnsNone
sorted()
method returns a new sorted list and does not modify the original list.sorted()
can be used on any iterable, not just lists. Example ofsorted()
method:
numbers_list = [42, 22, 27, 11, 34]
sorted_numbers = sorted(numbers_list)
print(numbers_list) # original order of elements: [42, 22, 27, 11, 34]
print(sorted_numbers) # sorted elements: [11, 22, 27, 34, 42]
Q: What happens if we try to sort a list with mixed data types?
If we try to sort a list that contains incompatible data types (like integers and strings), Python will raise a TypeError
. To handle such situations, you should ensure that all elements in the list are of a comparable type.
mixed_list = [32, 'shbytes', 22]
try:
mixed_list.sort()
except TypeError as e:
print(f"Error: {e}") # Error: '<' not supported between instances of 'str' and 'int'
sort()
method?
Q: How to sort a list in a custom order using the To sort a list in a custom order using sort()
method, we can provide a custom function to the key
parameter. This custom function can be used to define the sorting order.
courses_list = ['Python', 'Power BI', 'Java']
courses_list.sort(key=lambda x: len(x)) # sorting based on length of string
print(courses_list) # sorted list - ['Java', 'Python', 'Power BI'] (sorted by length)
Related Topics
- Append Elements to List – Python | Add Elements with Append MethodIn Python, elements in a list can be added using the append(element) method. This method allows us to add elements to the end of a list easily. In the previous articles, we explored accessing list elements by index and using the list index method to retrieve an element’s position. This article covers appending new elements…
- Concatenate Lists in Python – Complete Guide to List Concatenation MethodsConcatenation of lists in Python refers to merging of elements from two or more lists into a single list. Python provides a variety of methods for list concatenation, allowing flexibility based on the requirements of each task. For all topics related to lists, check out the Lists in Python: A Comprehensive Guide guide. In the…
- Count & Sort Methods in Python Lists: Tutorial with ExamplesThe count() & Sort() methods are built-in methods in Python lists, useful for counting occurrences of elements and sorting of elements in the list. Lists in Python can store duplicate elements and elements of various data types, making these methods essential for data handling. In previous article, we learned about Loops and List Comprehension in Python.…
- How to Access List Elements by Index in Python (with Example Programs)Python list elements are stored based on their index positions and can be accessed by their index positions, which allows to quickly retrieve specific element from the list. Index assignment to list element in Python, is similar to index assigned in Array elements. Understanding how to access list elements by index is crucial for data…
- How to Create List in Python | Python List Creation Methods ExplainedList is a sequence data type used to store elements (collection of data). Lists are similar to Arrays but have a dynamic size, meaning the list size can increase or decrease as elements are added or removed. A list is a core data type in Python, along with Tuple, Set and Dictionary. Lists in Python…