2 ms·
Exactly. To further elaborate, try the following in python, if you have the memory: >>> x = list(range(100000000)) + ["break"] After some time, you get a
by gcr 13y ago
Exactly. To further elaborate, try the following in python, if you have the memory:
>>> x = list(range(100000000)) + ["break"]
After some time, you get a list with a hundred million integers with a string at the end.
>>> len(x)
100000001
Now take the sum:
>>> sum(x)
On my machine, I get a traceback, but after about half a second of hesitation. Python's been iterating through each of those elements, testing to see if it's an integer and building a running sum, only to throw an exception because it didn't expect the string at the end. That means that in order to avoid memory corruption (or other terrible fates worse than an exception), Python must double-check each element of the list as it goes; it cannot take shortcuts.