0

Assuming 'm' is a series with index as 1,2,....12 and values as jan, feb,....dec,

var = 1
if var in m: 
      print(var*20)

In above, the condition checks if 'var' is present in the index of m (1,2.....12) and prints 20

But, when 'in' is used in a for statement, it iterates through the series' values instead of series' index

for var in m: 
      print(var) 

Above, prints all the month names (jan, feb..... dec)

Why is that the 'in' of the first piece of code (if block) searches in series index and the 'in' of the for statement iterates through the values of the series. Why is the behavior inconsistent ? Is there an explanation/logic behind this ?

tjt
  • 620
  • 2
  • 7
  • 17
  • @eyllanesc the question that was already answers (to which my question is a duplicate) doesn't seem to have clear answers or am I missing something ? Because answer say the in keyword looks for index (here index of the series), but not sure why the in of a for loop accesses the series values instead of index. Can you please explain/elaborate – tjt Sep 28 '21 at 05:22
  • I have not closed your question, just edit your post – eyllanesc Sep 28 '21 at 05:24
  • 1
    There is no guarantee of consistency between these two operations. You are operating from a false premise. – juanpa.arrivillaga Sep 28 '21 at 05:29
  • 1
    @tjt see the linked duplicate I added. [Here is a link to the docs](https://docs.python.org/3/reference/expressions.html#membership-test-operations) concerning the `x in y` membership testing expression. [Here is the documentation for iterable types](https://docs.python.org/3/library/stdtypes.html#typeiter) and the [glossary entry for iterable](https://docs.python.org/3/glossary.html#iterable) to for details about iterables/iterators in Python – juanpa.arrivillaga Sep 28 '21 at 05:39
  • @juanpa.arrivillaga The linked duplicates helps and they answer my question. Thank you very much – tjt Sep 28 '21 at 05:42

0 Answers0