Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Expanding upon Tobias' answer, using a <code>for</code> loop:</p> <pre><code>comp = [1, 2, 3] m = max(comp) for index in range(len(comp)): if comp[index] == m: # some action </code></pre> <p>Since indexing starts at 0, you <em>do not</em> need to do <code>len(comp) + 1</code>. I prefer using indexing in a <code>for</code> loop instead of the actual element, because it speeds things up considerably. Some times in a process, you may need the index of a specific element. Then, using <code>l.index(obj)</code> will waste time (even if only insignificant amounts --- for longer processes, this becomes tedious).</p> <p>This also assumes that every process (for the <code>comp[index]</code>) is very similar: same process but with different variables. This wouldn't work if you have significantly different processes for each index.</p> <p>However, by using <code>for index in range(len(l)):</code>, you already have the index and the item can easily be accessed with <code>l[index]</code> (along with the index, which is given by the loop).</p> <p>Oddly, it seems that Tobias' implementation is faster (I thought otherwise):</p> <pre><code>comp = [1, 2, 3] m = max(comp) from timeit import timeit def test1(): if comp[0] == m: return m if comp[1] == m: return m if comp[2] == m: return m def test2(): for index in range(len(comp)): if comp[index] == m: return m print 'test1:', timeit(test1, number = 1000) print 'test2:', timeit(test2, number = 1000) </code></pre> <p>Returns: </p> <pre><code>test1: 0.00121262329299 test2: 0.00469034990534 </code></pre> <p>My implementation may be faster for longer lists (not sure, though). However, writing the code for that is tedious (for a long list using repeated <code>if comp[n] == m</code>).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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