0
labeled_alphabet = pd.Series(list(ascii_uppercase), index=map(lambda x: 'label_' + x, list(ascii_uppercase)))

def every_fifth(x):
    return (True if (i+1) % 5 == 0 else False for i in range(x.size))
print(labeled_alphabet.iloc[every_fifth])

Since x is the input parameter how iloc is able to send the x without mentioning x in the function. For example I tried the following the code didnt error out but merely returned object.

<generator object every_fifth.<locals>.<genexpr> at 0x000001AE9E3E4F20>

Can someone explain what is happening here.

Also when to use [] and () This works

def every_fifth(x):
    return (True if (i+1) % 5 == 0 else False for i in range(x.size))
 

and also this works too:

def every_fifth(x):
    return [True if (i+1) % 5 == 0 else False for i in range(x.size)]
 

The moment I change to [] the above output is changed to [False, False, False, False, True, False, False, False, False, True, False, False, False, False, True, False, False, False, False, True, False, False, False, False, True, False] What is happening here.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • Your funtion returns the result of a generator expression, which of course, is a generator object. When you used a list comprehension, it created a list object. **Why did you expect anything else**? Clearly, you are aware of these syntactical constructs. Note, none of this has **anything** to do with `pandas` or the `.loc` method of pandas objects – juanpa.arrivillaga Mar 24 '22 at 21:27
  • Anyway, read the accepted answer in the linked duplicate for a good explanation of list comprehensions and generator expressions – juanpa.arrivillaga Mar 24 '22 at 21:28

0 Answers0