find the largest element in an array in python

To find the largest element in an array or list in Python, you can use the built-in max() function.

Here's an example of how to use it:

main.py
my_array = [3, 7, 1, 9, 4, 6, 8, 2, 5]
largest_element = max(my_array)
print("The largest element in the array is:", largest_element)
134 chars
4 lines

Output:

main.py
The largest element in the array is: 9
39 chars
2 lines

Alternatively, you can use a loop to traverse through the array and keep track of the maximum element. Here's an example:

main.py
my_array = [3, 7, 1, 9, 4, 6, 8, 2, 5]
max_element = my_array[0]

for element in my_array:
    if element > max_element:
        max_element = element

print("The largest element in the array is:", max_element)
211 chars
9 lines

Output:

main.py
The largest element in the array is: 9
39 chars
2 lines

Note that in this example, we initialize the max_element variable to the first element of the array, and then use a loop to compare each subsequent element to max_element and update it if a larger element is found.

related categories

gistlibby LogSnag