Christina
Christina

Reputation: 25

how to returns the index of the smallest element in the list in python

In my code, returns the position of the smallest element in the list by use index() function, when I run the code, it run nothing. Please help me to figure out problem. Here is what I coded:

def get_index_of_smallest(numbers):
    smallest_index = []
    for element in range (len(numbers)):
        element = numbers.index(min(numbers))
        smallest_index = element + 1
    return smallest_index

def test_get_index_of_smallest():
    list1 = [23, 3, 6, 5, 12, 9, 7, 4]
    print(get_index_of_smallest(list1))

Many thanks.

Upvotes: 2

Views: 1658

Answers (4)

vash_the_stampede
vash_the_stampede

Reputation: 4606

We can use list comprehension and enumerate here

min_idx = [idx for idx, item in enumerate(list1) if item == min(list1)]
[1]

Here is a expanded version of what is going on here

for idx, item in enumerate(list1):
    if item == min(list1):
        min_idx = idx

When we enumerate in it iterates for the index and item so what we can do is check each item v min(list1) if we get a match we can set our min_idx variable to the corresponding index of that item, cheers !

Upvotes: 0

Tolqinbek Isoqov
Tolqinbek Isoqov

Reputation: 175

You can use min(list) and builtin function of list(list.index())

list1 = [23, 3, 6, 5, 12, 9, 7, 4]
min_num = min(list1)
index = list1.index(min_num)

Upvotes: 2

Joe Patten
Joe Patten

Reputation: 1704

Your code looks good, but you forgot to call the function. Add test_get_index_of_smallest(), and it will work!

Input:

def get_index_of_smallest(numbers):
    smallest_index = []
    for element in range (len(numbers)):
        element = numbers.index(min(numbers))
        smallest_index = element + 1
    return smallest_index

def test_get_index_of_smallest():
    list1 = [23, 3, 6, 5, 12, 9, 7, 4]
    print(get_index_of_smallest(list1))

test_get_index_of_smallest()

Output:

2

Edit: You can further cut down your code. Here is a code that does the same thing:

Input:

def get_index_of_smallest(numbers):
    return numbers.index(min(numbers))+1

print(get_index_of_smallest([23, 3, 6, 5, 12, 9, 7, 4]))

Output:

2

Upvotes: 0

Transhuman
Transhuman

Reputation: 3547

One way, it's possible using min, emumerate and lambda

myList = [23, 3, 6, 5, 12, 9, 7, 4]
min(enumerate(myList), key=lambda x:x[1])[0]
#1

Upvotes: 0

Related Questions