Reputation: 141
I'm using Python 3.6. What would be an efficient way to check if a float or integer number within a list is negative or positive?
I want to iterate through a list, retrieving only the indexes of numbers of a particular sign.
For example:
x = [1,-7, 9, 3, 6, -3 ]
y = [ i for i in x if i **____** ]
I feel like its right under my nose, but its just not coming to me.
Upvotes: 1
Views: 4767
Reputation: 123463
Is this what you mean?
x = [1,-7, 9, 3, 6, -3 ]
y = [elem for elem in x if elem < 0]
z = [elem for elem in x if elem > 0]
print(y) # -> [-7, -3]
print(z) # -> [1, 9, 3, 6]
In this somewhat special case, you could use a slightly different approach and create both lists simultaneously:
x = [1,-7, 9, 3, 6, -3 ]
yz = y, z = [], []
for elem in x:
yz[elem > 0].append(elem) if elem else None
print(y) # -> [-7, -3]
print(z) # -> [1, 9, 3, 6]
Upvotes: 5