mapLast, mapFirst, and just general iterator questions

Leo usenet at gkbrk.com
Sun Jun 19 08:08:09 EDT 2022


On Wed, 15 Jun 2022 04:47:31 +1000, Chris Angelico wrote:

> Don't bother with a main() function unless you actually need to be
> able to use it as a function. Most of the time, it's simplest to
> just have the code you want, right there in the file. :) Python
> isn't C or Java, and code doesn't have to get wrapped up in
> functions in order to exist.

Actually a main() function in Python is pretty useful, because Python
code on the top level executes a lot slower. I believe this is due to
global variable lookups instead of local.

Here is benchmark output from a small test.

```
Benchmark 1: python3 test1.py
  Time (mean ± σ):     662.0 ms ±  44.7 ms
  Range (min … max):   569.4 ms … 754.1 ms
 
Benchmark 2: python3 test2.py
  Time (mean ± σ):     432.1 ms ±  14.4 ms
  Range (min … max):   411.4 ms … 455.1 ms
 
Summary
  'python3 test2.py' ran
    1.53 ± 0.12 times faster than 'python3 test1.py'
```

Contents of test1.py:

```
l1 = list(range(5_000_000))
l2 = []

while l1:
    l2.append(l1.pop())

print(len(l1), len(l2))
```

Contents of test2.py:

```
def main():
    l1 = list(range(5_000_000))
    l2 = []

    while l1:
        l2.append(l1.pop())

    print(len(l1), len(l2))
main()
```

-- 
Leo


More information about the Python-list mailing list