ravenUSMC
ravenUSMC

Reputation: 517

issue with count variable in Python while loop

I have an array of values:

increase_pop = [500, -300, 200, 100]

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:

max_value = increase_pop[0]
min_value = increase_pop[0]

count = 0
while count < len(increase_pop):
    if increase_pop[count] > max_value:
        max_year = count
        max_value = increase_pop[count]
    elif increase_pop[count] < min_value:
        min_value = increase_pop[count]
    count += 1

print(min_value)
print(max_value)

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:

UnboundLocalError: local variable 'max_year' referenced before assignment

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

Upvotes: 0

Views: 70

Answers (2)

jez
jez

Reputation: 15349

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

In your code, you could simply initialize max_year = count = 0

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

max_year, max_value = max( enumerate(increase_pop), key=lambda x: x[1] )

To unpack that: enumerate(increase_pop) generates a sequence of pairs:

(0, increase_pop[0]),   (1, increase_pop[1]), ...

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

Upvotes: 2

Howardyan
Howardyan

Reputation: 657

You can make your codes more pythonic by using the feature of list:

min_value = min(increase_pop)
max_value = max(increase_pop)
min_value_index = increase_pop.index(min_value)
max_value_index = increase_pop.index(max_value)

Upvotes: 2

Related Questions