简体   繁体   中英

What happens after getting max value of map object in Python

nums = map(int, input().split())
if max(nums)** 2 == next(nums)**2 + next(nums)**2:
  print(True)

Hi. I found out that when next(nums) is executed, stopIteration is raised. I thought only the max value of nums would be removed from nums after max(nums) was executed. But are all the values of nums removed after max function is executed? Looking forward to help! Thanks

All values are removed, since you are running through the entire iterator (all values) to find the max value. Which then removes all the values.

Ex:

>>> it = iter([1, 2, 3])
>>> max(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    next(it)
StopIteration
>>> 

The reason for this is because in order to find the maximum value, you need to loop through and use all the values in the iterator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM