0

How can I return the first element of in a list of tuples by finding the smallest postive number in the second element?

e.g

a_list = [(0,6),(1,2),(2,-2),(3,-5)]

to return 1?

elleh
  • 1
  • 1
  • 3
    What have you tried so far? – duckboycool Mar 06 '22 at 14:44
  • This question has been asked and answered [multiple](https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index) [times](https://stackoverflow.com/questions/17555218/python-how-to-sort-a-list-of-lists-by-the-fourth-element-in-each-list) [on](https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value) SO. The function you are looking for is [`sorted`](https://docs.python.org/3/howto/sorting.html). Please research before asking questions. – ramzeek Mar 06 '22 at 15:03

2 Answers2

0

You can do this by splitting your original list into two and then determining the smallest positive value in the second list. You can then print the index by passing it your smallest value, or use square bracket notation on your original list to return the tuple itself.

#Create the list
a_list = [(0,6),(1,2),(2,-2),(3,-5)]

#Split the tuple into two lists
first_element = [i[0] for i in a_list]
second_element = [i[1] for i in a_list]

#Find the smallest positive
smallest = min([i for i in second_element if i > 0])

#Return the index
where_in_list = second_element.index(smallest)

#Method 1
print(where_in_list)

#Method 2
a_list[where_in_list]

Output is 1 for Method 1 and (1, 2) for Method 2.

0

Try:

a_list = [(0,6),(1,2),(2,-2),(3,-5)]
#Currently set min value to first value for comparison
min = a_list[0][0]
#Loop through tuples in list
for n in range(len(a_list)):
  #If first value is 0, make min the next value for comparison
  if min == 0:
    min = a_list[n + 1][0]
  #To replace min value if the current value in iteration is less than the minimum value
  if a_list[n][0] < min and min != 0:
    min = a_list[n][0]

print(min) #To see minimum value
Sister Coder
  • 324
  • 1
  • 2
  • 12