issue with count variable in Python while loop
<p>I have an array of values:</p>

<pre><code>increase_pop = [500, -300, 200, 100]
</code></pre>

<p>I am trying to find the index of the lowest and highest values. Most of my code works and everything seems to be going well except for one problem. The rest of my code looks like the following:</p>

<pre><code>max_value = increase_pop[0]
min_value = increase_pop[0]

count = 0
while count &lt; len(increase_pop):
    if increase_pop[count] &gt; max_value:
        max_year = count
        max_value = increase_pop[count]
    elif increase_pop[count] &lt; min_value:
        min_value = increase_pop[count]
    count += 1

print(min_value)
print(max_value)
</code></pre>

<p>This code gets me the values of the min and max exactly what I want. However, I also want the index values of those positions. So for the max value I have the variable max_year = count assigned to it. Thus, I would think that max_year would be assigned to the count at the position where max_value was found. However, when I do a print(max_year) I get the following error:</p>

<pre><code>UnboundLocalError: local variable 'max_year' referenced before assignment
</code></pre>

<p>Does anyone know what my (probably) small/minor issue is? What am I forgetting?</p>

<p><code>max_year</code> is assigned when the first <code>if</code> conditional is satisfied.  But if that never happens, <code>max_year</code> will never be assigned.  That situation will occur when <code>increase_pop[0]</code> (and hence the initial value of <code>max_value</code>) is the largest value in <code>increase_pop</code>: then <code>increase_pop[count] &gt; max_value</code> will never be true.</p>

<p>In your code, you could simply initialize <code>max_year = count = 0</code></p>

<p>However, IMO the neatest, most Pythonic solution is the one from Patrick Haugh's comment:</p>

<pre><code>max_year, max_value = max( enumerate(increase_pop), key=lambda x: x[1] )
</code></pre>

<p>To unpack that:  <code>enumerate(increase_pop)</code> generates a sequence of pairs:</p>

<pre><code>(0, increase_pop[0]),   (1, increase_pop[1]), ...
</code></pre>

<p>and the <code>max</code> operator takes the "maximum" such pair according to the criterion specified by the <code>key</code> (and that particular key function just says "only consider the second value in each pair").</p>

python loops