Python | Positions of maximum element in list (original) (raw)
Last Updated : 16 May, 2023
Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of maximum element of list. This task is easy and discussed many times. But sometimes, we can have multiple maximum elements and hence multiple maximum positions. Let’s discuss a shorthand to achieve this task in this case.
Method 1: Using max() + enumerate() + list comprehension In this method, the combination of above functions is used to perform this particular task. This is performed in two steps. In 1st, we acquire the maximum element and then access the list using list comprehension and corresponding element using enumerate and extract every element position equal to maximum element processed in step 1.
Python3
test_list
=
[
8
,
4
,
6
,
8
,
2
,
8
]
print
(
"The original list : "
+
str
(test_list))
temp
=
max
(test_list)
res
=
[i
for
i, j
in
enumerate
(test_list)
if
j
=
=
temp]
print
(
"The Positions of maximum element : "
+
str
(res))
Output
The original list : [8, 4, 6, 8, 2, 8] The Positions of maximum element : [0, 3, 5]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. max() + enumerate() + list comprehension performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method 2: Using numpy
Note: Install numpy module using command “pip install numpy”
The numpy library in python provides a function called “argwhere()” which can be used to find the indices of all occurrences of a specific value in an array.
Python3
import
numpy as np
test_list
=
[
8
,
4
,
6
,
8
,
2
,
8
]
print
(
"The original list : "
+
str
(test_list))
res
=
np.argwhere(np.array(test_list)
=
=
max
(test_list))
print
(
"The Positions of maximum element : "
+
str
(res))
Output:
The original list : [8, 4, 6, 8, 2, 8] The Positions of maximum element : [[0] [3] [5]]
Method 3: Using pandas
In this method we creates a series from the list, filters it using boolean indexing, and extracts the positions of the maximum value. The resulting positions are stored in a list and then printed.
Python3
import
pandas as pd
test_list
=
[
8
,
4
,
6
,
8
,
2
,
8
]
print
(
"The original list : "
+
str
(test_list))
series
=
pd.Series(test_list)
max_val
=
series.
max
()
res
=
series[series
=
=
max_val].index.tolist()
print
(
"The Positions of maximum element : "
+
str
(res))
Output:
The original list : [8, 4, 6, 8, 2, 8] The Positions of maximum element : [0, 3, 5]
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list.