itertools.takewhile

suggest change

itertools.takewhile enables you to take items from a sequence until a condition first becomes False.

def is_even(x):
    return x % 2 == 0

lst = [0, 2, 4, 12, 18, 13, 14, 22, 23, 44]
result = list(itertools.takewhile(is_even, lst))

print(result)

This outputs [0, 2, 4, 12, 18].

Note that, the first number that violates the predicate (i.e.: the function returning a Boolean value) is_even is, 13. Once takewhile encounters a value that produces False for the given predicate, it breaks out.

The output produced by takewhile is similar to the output generated from the code below.

def takewhile(predicate, iterable):
	for x in iterable:
		if predicate(x):
			yield x
		else:
			break

Note: The concatenation of results produced by takewhile and dropwhile produces the original iterable.

result = list(itertools.takewhile(is_even, lst)) + list(itertools.dropwhile(is_even, lst))

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Itertools Module:
* itertools.takewhile

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
63 Itertools Module
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve