0

I want to find positions of zeros in a list.

mylist = [0, 1 ,False,2, 0.0, 'a', 0]

all_items=[i for i in enumerate(mylist)]
# all_items=  [(0, 0), (1, 1), (2, False), (3, 2), (4, 0.0), (5, 'a'), (6, 0)]    
    
res1=[]
for i in enumerate(mylist):
    if i[1] is 0 or i[1] is 0.0:
        res1.extend([i])

# res1 =[(0, 0), (4, 0.0), (6, 0)] 

res2=[i for i in enumerate(mylist) if i[1] is 0 or i[1] is 0.0]

#res2=[(0, 0), (6, 0)]  

I supposed res1 and res2 to be equivalent, but they differs. Why 0.0 is not in res2?

RuD91
  • 1
  • 1
  • 2
    Use `==` rather than `is` – Barmar Dec 16 '20 at 21:27
  • 1
    What is the `all_items` variable for? You never use it. – Barmar Dec 16 '20 at 21:29
  • 2
    FYI, `[i for i in something]` can be simplified to just `list(something)`. And `res1.extend([i])` should be `res1.append(i)` – Barmar Dec 16 '20 at 21:30
  • 1
    I get the same result from the `for` loop and the list comprehension. I had to change from `mylist` to `Mylist`. – Barmar Dec 16 '20 at 21:38
  • Just try `print(all_items[4][1] is 0.0)` and you'll see that it's not true. – Barmar Dec 16 '20 at 21:39
  • Ok, `all_items[4][1] is 0.0` is `False`, then why `0.0` in `res1` ? – RuD91 Dec 16 '20 at 21:43
  • It isn't in `res1` when I try it. – Barmar Dec 16 '20 at 21:43
  • Comparing identity (is) and equality (==) are different things. The former is stronger than the later. It is equal and the same object. – jlandercy Dec 16 '20 at 21:44
  • Hmm, I get your results when I try it on ideone.com. Maybe the difference is that I did my test in the REPL rather than running a script. – Barmar Dec 16 '20 at 21:45
  • It seems like it has something to do with optimizations done when compiling the script, related to how `is` is compiled in the two contexts. But you shouldn't depend on `is` this way,. – Barmar Dec 16 '20 at 21:47
  • I've tried it in my IDE and here [link](https://www.onlinegdb.com/online_python_interpreter). Python ver. 3.7 and 3.4. And got the same results. `res1` and `res2` are different. – RuD91 Dec 16 '20 at 21:50
  • Thank you, @Barmar! I know that it is better to use `==` instead `is`, but I cant understand the reason of different behavior. You pointed the reason. – RuD91 Dec 16 '20 at 22:00

0 Answers0