Python – Maximum element in Cropped List

Sometimes, while working with Python, we can have a problem in which we need to get maximum of list. But sometimes, we need to get this for between custom indices. This can be need of any domain be it normal programming or web development. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop + max()
This is brute force method in which we performed this task. In this, we just add to new list the elements in specified range. Then max() is used to compute maximum.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Maximum element in Cropped List
# using loop + max()
  
# initializing list 
test_list = [2, 3, 5, 7, 9, 10, 8, 6]
  
# printing original list
print ("The original list is : " + str(test_list))
  
i, j = 2, 5
  
# Maximum element in Cropped List
# using loop + max()
res = []
for idx, ele in enumerate(test_list):
    if idx >= i and idx < j:
        res.append(ele)
res = max(res)
  
# printing result 
print ("The maximum element in range is : " + str(res))

chevron_right


Output :



The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The maximum element in range is : 9

 

Method #2 : Using list slicing + max()
The combination of above functions can be used to perform this task. In this, we just perform slicing using list slicing and max() performs the task of extracting max.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Maximum element in Cropped List
# using list slicing + max()
  
# initializing list 
test_list = [2, 3, 5, 7, 9, 10, 8, 6]
  
# printing original list
print ("The original list is : " + str(test_list))
  
i, j = 2, 5
  
# Maximum element in Cropped List
# using list slicing + max()
res = test_list[i : j]
res = max(res)
  
# printing result 
print ("The maximum element in range is : " + str(res))

chevron_right


Output :

The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The maximum element in range is : 9



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.