MechMon MechMon - 2 months ago 12
Python Question

if elif else blocks evaluate for every case

I am trying to append an iterator to a list but my code below evaluates for every case.

Less7=Head7=Over7=[]
i=0

for i in range(0,10):
if i<7:
Less7.append(i)

elif i==7:
Head7=i

else:
Over7.append(i)


The result I am getting are:
Head7 is an int value of 7
Less7 and Over7 are lists - [0,1,2,3,4,5,6,7,8,9]

My desired results are:

Less7=[0,1,2,3,4,5,6]

Head7=[7]

Over7=[8,9]


I'm sure it's basic, could you point me in the right direction?
My thought is that it has to do with the datatype.
When I step through the code, even
Head7
evaluates
[0,1,2,3,4,5,6]
but when
i=7
then it correctly assigns the value, but I want it in a list.

Answer

You need to create three lists, one for each possible outcome:

less_than_7, is_7, greater_than_7 = [], [], []

for i in range(0, 10):
    if i < 7:
        less_than_7.append(i)
    elif i > 7:
        greater_than_7.append(i)
    else:
        is_7.append(i)

Less7=Head7=Over7=[] creates one list that is referenced by the three names so your output would be identical as you are appending to the same list, well you are in the first and last case, Head7=i sets Head7 equal to i/7.