find the smallest element in an array in python

To find the smallest element in an array in Python, you can use a combination of sorting and indexing. Here's one way to do it:

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

# Sort the array in ascending order
my_array.sort()

# The smallest element will be at index 0
smallest_element = my_array[0]

print(smallest_element)
191 chars
10 lines

This will output:

main.py
1
2 chars
2 lines

Alternatively, you can use a loop to compare each element of the array to a variable that stores the current smallest element. Here's an example:

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

# Set the current smallest element to the first element of the array
smallest_element = my_array[0]

# Loop through each element of the array
for element in my_array:
    # If the current element is smaller than the current smallest element,
    # update the value of the current smallest element
    if element < smallest_element:
        smallest_element = element

print(smallest_element)
432 chars
14 lines

This will also output:

main.py
1
2 chars
2 lines

gistlibby LogSnag