max() of big nested lists
<p>I encountered a quite odd problem while dealing with the max of a long list of lists of of pairs, such as</p>

<pre><code>[
    [(0, 1), (1, 1), (2, 1), (3, 4), (4, 1), (5, 1), (6, 1),...,(141,3)],
    ..., 
    [(12, 1), (36, 1), (91, 1), (92, 1), (110, 1),..., (180, 1)]
]
</code></pre>

<p>I am trying to get the maximum of the first element of all the pairs.
Pythonically, I was doing:</p>

<pre><code>max([max(x) for x in list])[0]
</code></pre>

<p>which actually returns the correct number, IF the list is shorter than 281 lists.
In fact, as soon as the list is longer than 280, I get this message</p>

<pre><code>ValueError: max() arg is an empty sequence
</code></pre>

<p>So, for a long list</p>

<pre><code>max([max(x) for x in list[0:280]])[0]
</code></pre>

<p>it's fine, while</p>

<pre><code>max([max(x) for x in list[0:281]])[0]
</code></pre>

<p>breaks.</p>

<p>Am I doing something wrong here?</p>

<p>You have an empty list among your list of lists, at index 280. Slicing up to <code>[:280]</code> excludes it, and it is included with <code>[:281]</code>.</p>

<p>This is easily reproduced with a shorter sample:</p>

<pre><code>&gt;&gt;&gt; lsts = [
...     [(0, 1), (1, 1)],
...     [(2, 1), (3, 4)],
...     [(4, 1), (5, 1)],
...     [],  # empty at index 3
... ]
&gt;&gt;&gt; max(max(x) for x in lsts)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "&lt;stdin&gt;", line 1, in &lt;genexpr&gt;
ValueError: max() arg is an empty sequence
&gt;&gt;&gt; max(max(x) for x in lsts[:3])  # include everything before index 3
(5, 1)
</code></pre>

<p>You can avoid the issue altogether by chaining your lists together, here using <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>chain.from_iterable()</code></a>:</p>

<pre><code>from itertools import chain

max(chain.from_iterable(list_of_lists))[0]
</code></pre>

<p>This treats all nested lists as one long list, an empty list somewhere in between simply doesn't contribute to that new sequence.</p>

python list max nested-lists