147k views
3 votes
(Find the index of the smallest element) Write a function that returns the index of the smallest element in a list of integers. If the number of such elements is greater than 1, return the smallest index. Use the following header: def indexOfSmallestElement(lst): Write a test program that prompts the user to enter a list of numbers, invokes this function to return the index of the smallest element, and displays the index.

1 Answer

1 vote

Answer:

Here is the function that returns the the smallest element in a list of integers

def indexOfSmallestElement(lst):

smallest = lst.index(min(lst))

return smallest

Step-by-step explanation:

The function indexOfSmallestElement() takes a list of integers lst as parameter.

smallest = lst.index(min(lst))

In the above statement two methods are used i.e. index() and min().

The first method index returns the index position of the list and the second method min() returns the minimum element of the list.

Now as a whole the statement min() first returns the smallest element in the list (lst) of integers and then the index() method returns the position of that minimum element of lst. At the end the index position of this smallest element in the list (lst) is stored in the smallest variable.

So lets say if we have a list of the following elements: [3,2,1,7,1,8] then min() returns the smallest element in this list i.e. 1 and index() returns the index position of this smallest element. Now notice that 1 occurs twice in the list and index() method only returns the the first index found in the list. So it returns the smallest index of the two index positions of 1 i.e 2. Hence the output is 2.

The test program is given below:

lst=list()

num=int(input("Enter the list size: "))

print("Enter a list of numbers: ")

for i in range(int(num)):

integers=int(input(""))

lst.append(integers)

print("The index of the smallest element is: ")

print(indexOfSmallestElement(lst))

First the list named lst is created. After that the user is prompted to enter the size of the list which determines how many elements user wants to add to the list. num holds the size input by user. After that print statement displays the line"Enter a list of numbers: ". Next the for loop takes the integers from user num times. Suppose user want to enter 3 as list size then loop will take 3 elements from user. int(input("")) in this statement integer type input is taken from user using input() method. lst.append(integers) statement is used to append these input integers into the list i.e. lst. print(indexOfSmallestElement(lst)) the statement calls the indexOfSmallestElement by passing lst to this method to return the index of the smallest element in the list of integers.

(Find the index of the smallest element) Write a function that returns the index of-example-1
User Stamm
by
5.5k points