Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, I would stick with <code>itervalues</code>, which uses easy evaluation.</p> <p>Second, I would be wary of relying on using <code>set</code> since it performs looking up the value in the set on every iteration of going through dictionary. It's <code>O(1)</code> on the overage (and <code>O(n)</code> in the worse case which is <code>O(1)</code> in our case if all the length are the same, and <code>O(n)</code> if all the length are different) according to the <a href="http://wiki.python.org/moin/TimeComplexity" rel="nofollow">docs</a>. But it's difficult to asses the overhead of using set.</p> <p>I would use <code>all</code> in this case. <code>all</code> fails when it finds the first <code>False</code> value. So, the first mismatch of the length would stop the interating process. While, if using <code>set</code>, it would go through <strong>all the list</strong> to the end and only then compare its length to <code>1</code>.</p> <pre><code>&gt;&gt;&gt; dct = {'a': [1, 2, 3], 'b': [1, 2, 3, 4], 'c': [1, 2]} &gt;&gt;&gt; lenght_1 = len(dct.itervalues().next()) &gt;&gt;&gt; all(len(value)==lenght_1 for value in dct.itervalues()) False &gt;&gt;&gt; dct = {'a': [1, 2, 3], 'b': [1, 2, 4], 'c': [1, 2, 5]} &gt;&gt;&gt; lenght_1 = len(dct.itervalues().next()) &gt;&gt;&gt; all(len(value)==lenght_1 for value in dct.itervalues()) True </code></pre> <p>The code can be optimized by using the same iterator <code>it</code> which will not go through the first value twice:</p> <pre><code>&gt;&gt;&gt; it = dct.itervalues() &gt;&gt;&gt; length_1 = len(next(it)) &gt;&gt;&gt; all(len(value)==l1 for value in it) True </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload