Scaramouche Studio
Scaramouche Studio

Reputation: 41

'<' not supported between instances of 'str' and 'int'

I need some help with Python3, please

I've got a simple code, which turns the even minimum of the list into the string

source_array = [5,2,3,7]
i = 0
    
while min(source_array) % 2 == 0:
    i = source_array.index(min(source_array))
    source_array[i] = str(source_array[i])

it gives me an error: '<' not supported between instances of 'str' and 'int'

I'd think, that it's just a language feature, but such code works perfectly:

b = [5,2,3,7]
b[1] = str(b[1])
print(b)
Output:
[5, '2', 3, 7]

what is the reason of such behaviour?

Upvotes: 2

Views: 1116

Answers (2)

Ismail Durmaz
Ismail Durmaz

Reputation: 2621

You must eliminate not int values to get minimum. You can use lambda function to get a new list only contains int values

source_array = [5,2,3,7]
i = 0
    
while min(list(filter(lambda x: type(x) == int, source_array))) % 2 == 0:
    i = source_array.index(min(source_array))
    source_array[i] = str(source_array[i])

print(source_array)

Output

[5, '2', 3, 7]

Edit:

I have checked if there are 4 number without 3. The algorithm is not working again. I have to define filter and lambda expressions into source_array.index(...). However, I don't like to define the same command more than once. Maybe you can use a variable for a temporary list.

Note if all numbers are even, you will get another error, you should check are there any items as int?

source_array = [5,2,4,7]
i = 0
    
while min(list(filter(lambda x: type(x) == int, source_array))) % 2 == 0:
    i = source_array.index(min(list(filter(lambda x: type(x) == int, source_array))))
    source_array[i] = str(source_array[i])

print(source_array)

Output:

[5, '2', '4', 7]

More even numbers and a single odd number.

source_array = [12, 4, 8, 6, 15]

['12', '4', '8', '6', 15]

Upvotes: 2

Vityata
Vityata

Reputation: 43575

This one works quite ok:

source_array = [5,2,3,7]
i = 0
    
if min(source_array) % 2 == 0:
    i = source_array.index(min(source_array))
    source_array[i] = str(source_array[i])
print(source_array)

The problem is in the loop, the second time it goes in the while, it is comparing string and int and it does not like it.

Upvotes: 1

Related Questions