Skip to content

Instantly share code, notes, and snippets.

@drobati
Created February 22, 2016 15:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drobati/00ffe2500550a0a0bf31 to your computer and use it in GitHub Desktop.
Save drobati/00ffe2500550a0a0bf31 to your computer and use it in GitHub Desktop.
Return list until match is found
list(gen)
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
items = list()
try:
while gen:
item = next(gen)
items.append(item)
if item == '4': break
except StopIteration:
print "log a message"
pass
@drobati
Copy link
Author

drobati commented Feb 22, 2016

Is there a more efficient means of producing ['0', '1', '2', '3', '4']?

@Ianleeclark
Copy link

>>> print list(takewhile(lambda x: x != '4', ['0', '1', '2', '3', '4', '5']))
['0', '1', '2', '3']

@drobati
Copy link
Author

drobati commented Feb 22, 2016

Based on https://bpaste.net/show/e35bbcd193a7 via BlaXpirit

items = []
for item in gen:
    items.append(item)
    if item == '4': break
else:
    print "Match was not found."

@Ianleeclark
Copy link

$ python -m cProfile test_append.py
         8 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 test_append.py:1(<module>)
        1    0.000    0.000    0.000    0.000 test_append.py:3(main)
        5    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Where test_append.py is

1   gen = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  1
  2 def main():
  3     items = []
  4     for item in gen:
  5         items.append(item)
  6         if item == '4':
  7             return items
  8     else:
  9         print 'Match was not found'
 10
 11 if __name__ == "__main__":
 12     main()
$ python -m cProfile test_slice.py
         3 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 test_slice.py:1(<module>)
        1    0.000    0.000    0.000    0.000 test_slice.py:3(main)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Where test_slice is

  1 gen = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
2
  1 def main():
  2     for i, item in enumerate(gen):
  3         if item == '4':
  4             return gen[0:i + 1]
  5
  6 if __name__ == "__main__":
  7     main()

Take it as you will.

@drobati
Copy link
Author

drobati commented Feb 22, 2016

Thanks @GrappigPanda

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment