MechMon - 1 year ago 86
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:

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]

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.

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`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download