Why doesn’t `is` reliably detect the largest value in my Python list?
Asked by
MellowQuartz42
I have a smaller function from a larger program that should add values from a list until it reaches the largest element, then stop:
```python
def streak_call(ste):
stroik = 0
for st in ste:
if st is max(ste):
break
stroik += st + 1
return stroik
```
The function is not behaving consistently, and I suspect the `is` comparison is the problem. Why doesn't this work reliably, and what should I use instead?
Answers
`is` checks object identity—it asks whether both sides refer to the exact same object. For comparing values, use `==` instead:
```python
if st == max(ste):
break
```
`max(ste)` returns the largest value in the list, but relying on it being the same object as `st` is not safe. Identity comparisons can appear to work with some integers because of implementation details such as integer caching.
Reply to this answer
You can also calculate the maximum once before the loop instead of recalculating it on every iteration:
```python
def streak_call(ste):
largest = max(ste)
total = 0
for value in ste:
if value == largest:
break
total += value + 1
return total
```
This is clearer and more efficient. Just remember that `max(ste)` raises an error if `ste` is empty.
Reply to this answer
One other thing to check is `stroik += st + 1`. That adds one extra to every value before the largest item. If you intended to return the plain sum of the preceding values, use `total += value` instead. If the extra one is intentional, then the original expression is fine.
Reply to this answer
Add your answer
Answers are reviewed before publication.
MellowQuartz42: So `is` may seem to work with some integer lists, but that behavior isn’t something the code should depend on. `==` is the correct comparison here.