Why doesn’t `is` reliably detect the largest value in my Python list?

0
0
Asked By MellowQuartz42 On

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?

3 Answers

Answered By CopperLynx53 On

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.

Answered By KindleRiver18 On

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.

Answered By BrightOtter7 On

`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.

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.