Find a maximum of a list without constructing the list

python

Solution

`max()` takes a generator also:

max(f(k) for k in range(n))

This saves you from having to build the entire list.

Thanks to @DanielRoseman for pointing out that in Python 2.x you should be using `xrange()` instead of `range()`. Recall that `range()` returns a list in Python 2.x, whereas `xrange()` returns an `xrange object` (a constant-memory iterable).

Problem

I've been playing around with Python for making one-line solutions for some competition problems, and I've run into the following issue. My solution can be written as `max([f(k) for k in range(n)])` (where `f(k)` is some simple expression), which looks great, but when `n` is large it ends up constructing a list before finding its maximum, which exceeds the memory limit. Is there a way to find the maximum without actually constructing the list, while still keeping it down to one line? I know the following works, but if I wanted that I'd just use a different language: ``` best = f(0) for k in range(n): best = max(best, f(k)) return best ```

Original source