{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/skip-first-part-of-an-iterable/",
  "description": "Skip elements in iterables until a condition is met using itertools.dropwhile for efficient lazy evaluation that works with generators.",
  "path": "/python/skip-first-part-of-an-iterable/",
  "publishedAt": "2023-02-12T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python",
    "TIL"
  ],
  "textContent": "Consider this iterable:\n\nLet's say you want to build another iterable that includes only the numbers that appear\nstarting from the element 0. Usually, I'd do this:\n\nWhile this is quite terse and does the job, it won't work with a generator. There's an even\nmore generic and terser way to do the same thing with itertools.dropwhile function. Here's\nhow to do it:\n\nHere, itertools.dropwhile is a generator function that returns elements from an iterable\nstarting from the first element for which the predicate returns False. The predicate is a\nfunction that takes one argument and returns a boolean value.\n\nThe dropwhile function takes two arguments:\n\n- A function (the predicate), which takes one argument and returns a boolean value.\n- An iterable, which can be any object that can be iterated over, such as a list, tuple,\n  string, or even another generator.\n\nThe dropwhile function starts iterating over the elements of the iterable, and drops the\nelements for which the predicate returns True. It then returns all the remaining elements\nof the iterable, regardless of whether they satisfy the condition or not.\n\nApart from being concise, this implementation is more generic and can be used for other\npurposes like skipping the header lines in a file. For example:\n\nThis will print all the lines from the /etc/passwd file after the header comments:\n\nFinally, let's see how you can skip straight to the data rows in a CSV file that contains\narbitrary comments and headers like this:\n\nRunning this will give you the dicts containing the data rows only:\n\nFurther reading\n\n- [Python Cookbook - David Beazley, Ch 4: Iterators and Generators]\n- [itertools.dropwhile]\n\n\n\n\n[python cookbook - david beazley, ch 4: iterators and generators]:\n    https://www.oreilly.com/library/view/python-cookbook-3rd/9781449357337/\n\n[itertools.dropwhile]:\n    https://docs.python.org/3/library/itertools.html#itertools.dropwhile",
  "title": "Skipping the first part of an iterable in Python"
}