-1

I came across this useful bit of code that returns the indexes of the minimum values of a list l

[i for i, x in enumerate(l) if x == min(l)]

Could someone help me with what this way of creating a list is called and/or what the process is? I'm familiar with [i*2 for i in l] type code but I'm not familiar with what the comma does and what the reason for defining a new variable x is.

Many Thanks

Thanos Dodd
  • 500
  • 1
  • 3
  • 9

3 Answers3

0

The enumerate function returns a tuple of size 2, the first being the index, and the second being the element at that index in the list. We can assign a tuple to numerous variables in the form:

>>> i, v = (1, 2)
>>> i
1
>>> v
2

So in your example, it loops over the list, and for each index and value in the list, checks if the value is equal to the minimum value in the list. If so, it appends i to the list comprehension.

Of course, the list comprehension is equal to:

[l.index(min(l))]
CDJB
  • 13,204
  • 5
  • 27
  • 47
0

Enumerates returns a tuple index, element of your list l, you just tell python to assign the first element of the tuple (the index) to i, and your element to x everytime Next is called.

Maxime
  • 736
  • 6
  • 18
0

This method of list creation is called "List comprehention", while using enumerate the 'i' in "i, x" indicates a index number(or serial number if you prefer) and x represents the iterations in the lists (for example in list = [1,2,3,4] the number each number is a single iteration)

so, when the code [i for i, x in enumerate(l) if x == min(l)] is passed it would create a list of indexes that least iteration value attached to it since the function min() is used.