0

Here is a sample code to do it,

def func():
    return something

# I want to break the list comprehension at the first None.
# The walrus := is valid in Python 3.8
items = [r for _ in range(100) if (r := func()) is not None]
# else break?

I wonder if it is possible that break in list comprehension with any method, such as takewhile or others?

Ken Nieh
  • 95
  • 2
  • 10
  • Something like this? `[z for z in takewhile(lambda x:x<3,[1,2,3,4,5])]` (using `takewhile` from `itertools`) – Scott Hunter Aug 21 '19 at 16:33
  • 1
    [Short-circuiting list comprehensions \[duplicate\]](https://stackoverflow.com/q/16931214/674039) – wim Aug 21 '19 at 16:34
  • @ScottHunter At that point, though, there's little reason to use a list comprehension instead of just passing the `takewhile` instance directly to `list`. – chepner Aug 21 '19 at 16:34
  • 1
    @chepner: I didn't say it was a good idea... – Scott Hunter Aug 21 '19 at 16:35
  • @ScottHunter Your sample really can break it, but I want to break it by some function return not the range(100) – Ken Nieh Aug 21 '19 at 16:39
  • @win It's not duplicate, Your link don't break it, and I want to break it with some function return not the range(100) – Ken Nieh Aug 21 '19 at 16:43
  • What about https://stackoverflow.com/a/7238861/674039 – wim Aug 21 '19 at 17:40

1 Answers1

1

List comprehension, no; it's basically syntactic sugar for map and filter. But takewhile and map will provide a suitable input for list, as you suspect.

items = list(takewhile(lambda x: x is not None, map(func, ...)))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • items = list(takewhile(lambda x: x is not None, map(func, range(100)))), It works very well. Thanks! – Ken Nieh Aug 21 '19 at 16:56