Take while

Whereas Python’s islice (and Haskell’s take and drop) cut some number of elements from a list, the corresponding takewhile itertools.takewhile and dropwhile inspect the list’s values and truncate the list based on what it contains.

The general concept of taking is to keep some portion of beginning of a series and ignore the remainder.

And dropping is to discard some things we don’t care about from the beginning of a series, and get only the remainder.

take and takewhile are both ways of taking, and drop and dropwhile are both ways of dropping. The difference is how they determine how much of the series to take or drop.

takewhile

Here we take characters from a string while they are lower-case. The resulting iterator stops at the first place it encounters an upper-case letter.

>>> it = takewhile(lambda x: x.islower(), 'oneTwoThree')

>>> ''.join(it)
'one'

Haskell’s function is also called takeWhile takeWhile in Data.List and Prelude (though note the capital W).

λ> import Data.Char (isLower)

λ> takeWhile isLower "oneTwoThree"
"one"

dropwhile

takewhile also has a companion named dropwhile, itertools.dropwhile which removes elements matching the predicate from the beginning of the list and returns the remainder.

Here we drop characters from the string while the characters are lower case. The result we get is the rest of the string starting from the first upper-case letter.

>>> it = dropwhile(lambda x: x.islower(), 'oneTwoThree')

>>> ''.join(it)
'TwoThree'

Again, the Haskell function is the same. dropWhile in Data.List and Prelude

λ> dropWhile isLower "oneTwoThree"
"TwoThree"

span: Taking and dropping at the same time

takeWhile and dropWhile are opposites; takeWhile takes the part of the list that dropWhile drops. It is not uncommon to want to perform both of these actions at once, thereby splitting a list into two parts:

  1. The beginning in which all elements satisfy the predicate, and
  2. the remainder starting from the first element that does not satisfy the predicate.

This is what Haskell’s span function span in Data.List and Prelude does: it combines takeWhile and dropWhile into a single function that gives both results.

λ> span isLower "oneTwoThree"
("one","TwoThree")

Join Type Classes for courses and projects to get you started and make you an expert in FP with Haskell.