Guido van Rossum wrote: > But I think the logical consequence of your approach would be that > sum([]) should raise an exception rather than return 0, which would be > backwards incompatible. Because if the identity element has a default > value, the default value should be used exactly as if it were > specified explicitly. > > Unfortunately my proposal is also backwards incompatible, since > currently sum([1,1], 40) equals 42. Somewhat ugly, but backwards compatible: sentinel = object() def sum(iterable, initial=sentinel): itr = iter(iterable) if initial is not sentinel: # Initial value provided, so use it value = initial else: try: first = itr.next() except StopIteration: # Empty iterable, return 0 for backwards compatibility # Also correct for standard numerical use return 0 # Assume default constructor returns the additive identity value = type(first)() value += first # Add the elements for item in itr: value += item return value Py> sum([]) 0 Py> seq = ([1], [2], [3]) Py> sum(seq) [1, 2, 3] Py> seq ([1], [2], [3]) Py> seq = ('1', '2', '3') Py> sum(seq) '123' Py> seq ('1', '2', '3') Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4