George Zhao
George Zhao

Reputation: 19

checking multiple if statements

let's say I wanted to organize a list of numbers by positive, negative, and floats. how would I get this code to add a number to multiple lists such as pos and flt? For example 5.6. instead of just adding it to pos and moving on to the next one with out checking if 5.6 is a float as well?

list_num=[1,-1,-3,5.6,9.0]
neg=[]
pos=[]
flt=[]
for n in list_num:
    if n<0:
        neg.append(n)
    if n>=0:
        pos.append(n)
    if str(n).isdigit()==False and n>0:
        flt.append(n)

print neg
print pos
print flt

Upvotes: 0

Views: 49

Answers (1)

user
user

Reputation: 5696

If i understand correctly, you want to create each list separately. If so, list comprehensions can help you create each list in one go, without checking the other conditions.

neg = [i for i in list_num if i < 0]
pos = [i for i in list_num if i > 0]
flt = [i for i in list_num if isinstance(i, float)] 

Upvotes: 1

Related Questions