2
n = 4
v = [16, 19, 23, 28]
w = [2, 3, 4, 5]

idxs = list(range(n))
idxs.sort(key=lambda i: v[i]/w[i], reverse=True)  

objs = ((v[i], w[i]) for i in idxs[m:]) 
for av, aw in objs:
    print av
    print aw

I came across the above chunk of code. If m=2, it returns 23 4 28 5. I wonder how does the below indicated line of code work in Python, is this a function call? or what?. Would you point me to Python 2.7 manual which explain this feature? I'd properly need a better title for this question, but I don't know how to name it, any suggestion?

objs = ((v[i], w[i]) for i in idxs[m:])
twfx
  • 1,664
  • 9
  • 29
  • 56

1 Answers1

4

That's a generator expression, also sometimes called a generator comprehension. The last four lines of code are basically equivalent to

for i in idxs[m:]:
    av, aw = v[i], w[i]
    print av
    print aw
Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187