Homap
Homap

Reputation: 2214

Find the smallest element in a list of list

Given the following list:

f = [[1, 19], [1, 19], [1, 19], [2, 18], [16, 4], [10, 10]]

I want to get the smallest value of each sub-list and create:

f1 = [1, 1, 1, 2, 4, 10]

How can I do this?

Upvotes: 9

Views: 1086

Answers (3)

ThePyGuy
ThePyGuy

Reputation: 18466

Since it's a Python list, you can use min function for each sub-list using list-comprehension

[min(subList) for subList in f]

OUTPUT:

[1, 1, 1, 2, 4, 10]

Or, you can even combine min and map together

list(map(min,f))

Upvotes: 16

Muhammad Safwan
Muhammad Safwan

Reputation: 1024

you can use builtin min function

f = [[1, 19], [1, 19], [1, 19], [2, 18], [16, 4], [10, 10]]
f1 = []
for i in f:
    f1.append(min(i))
f1

Upvotes: 7

sacuL
sacuL

Reputation: 51425

An easy numpy way would be to use axis=1 with np.min:

>>> f1 = np.min(f, axis =1) 
>>> f1
array([ 1,  1,  1,  2,  4, 10])

A non-numpy way could be to map min to f:

>>> list(map(min, f))
[1, 1, 1, 2, 4, 10]

Upvotes: 9

Related Questions