You are viewing a single comment's thread. Return to all comments →
Guys! I have a question related to Python, in this piece of code of yours - [x for x in numbers if x>0].
What if I wanted to create a "new list" (which contains only negative numbers) from "numbers list" where numbers list is sorted in ascending order. I want to break the loop when x>= 0. So,
a = [x for x in numbers if x >= 0: break]
As you know this syntax is wrong, can you guys suggest me what is the proper way? I am new to Python.
There is no recommended way to interrupt an "expression" loop (i.e., comprehension, filter, map, reduce). You must use a conventional loop.
More on this, with a hack: http://stackoverflow.com/questions/9572833/break-list-comprehension
Depends if you really need to break.
If not -- simply:
## list comprehension to get only neg numbs
a = [i for i in num_list if i < 0]
## if u want to break
for i in num_list:
if i >= 0: