0

val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

This statement gives the minimum and the index of that minimum. I am curious to know how this works.

I did type((value, index) for index, value in enumerate(percent_chance_per_stock) if value > 0) and got <class 'generator'>. How does it work in conjunction with min function and return a tuple?

Frank Shrestha
  • 103
  • 1
  • 6
  • 1
    It looks simple, but to actually understand it see [Understanding generators in Python - Stack Overflow](https://stackoverflow.com/questions/1756096/understanding-generators-in-python) – user202729 Feb 22 '21 at 11:21
  • 1
    You also have to know how tuple comparison are performed. – user202729 Feb 22 '21 at 11:21
  • I did see the link you posted and I know about generators already but couldn't figure how this is working. I am just new to python and when I stumble upon these things I want to know how these work. Thanks I think I should look tuple comparisons then. – Frank Shrestha Feb 22 '21 at 11:27
  • Is it that the min function is applied to the first elements of all tuples and when found the minimum, it just returns that tuple? – Frank Shrestha Feb 22 '21 at 11:41
  • Hi, @FrankShrestha -do you get it now? Or still need some explanations on it? – Daniel Hao Feb 22 '21 at 15:35

1 Answers1

0

Here is step-by-step action if not using generator expression:

>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 0, 9]
>>> #                              ^     <- '0' is the smallest num. @8th pos.
>>> # the generator version: saving the tmp_list and faster
>>> val, idx = min((val, idx) for idx, val in enumerate(lst))
>>> print(f' minimum num: {val}, position: {idx} ')
 minimum num: 0, position: 8 
>>> # now it's more steps for storing the num->idx in the tmp_list first:
>>> tmp_lst = []
>>> for idx, val in enumerate(lst):
    tmp_lst.append((val, idx)) # store num, idx but in reverse order

    
>>> tmp_lst
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6), (8, 7), (0, 8), (9, 9)]
>>> min(tmp_lst)   # gives the (nums, idx)  It works, since tuple comp. by order
(0, 8)
>>> 
Dharman
  • 30,962
  • 25
  • 85
  • 135
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23