How to Take the First N Items from a Generator or List

How to take the first N items from a generator or list?

Slicing a list

top5 = array[:5]
  • To slice a list, there's a simple syntax: array[start:stop:step]
  • You can omit any parameter. These are all valid: array[start:], array[:stop], array[::step]

Slicing a generator

import itertools
top5 = itertools.islice(my_list, 5) # grab the first five elements
  • You can't slice a generator directly in Python. itertools.islice() will wrap an object in a new slicing generator using the syntax itertools.islice(generator, start, stop, step)

  • Remember, slicing a generator will exhaust it partially. If you want to keep the entire generator intact, perhaps turn it into a tuple or list first, like: result = tuple(generator)

How to take the first n element from an infinite Generator List?

itertools.islice does exactly that, though in your example you need to be careful to not repeatedly yield a reference to the same object that keeps getting modified:

def infiniList():
count = 0
ls = []
while True:
yield ls[:] # here I added copying
count += 1
ls.append(count) # or you could write "ls = ls + [count]" and not need to make a copy above

import itertools
print(list(itertools.islice(infiniList(), 5)))

How to get the n next values of a generator in a list (python)

Use itertools.islice:

list(itertools.islice(it, n))

How to take the first N elements from a Generator in Julia

You can use Iterators.take.

Try collect(Iterators.take(odds, 10))

Remove the first N items that match a condition in a Python list

One way using itertools.filterfalse and itertools.count:

from itertools import count, filterfalse

data = [1, 10, 2, 9, 3, 8, 4, 7]
output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data)

Then list(output), gives you:

[10, 9, 8, 4, 7]

Get the nth item of a generator in Python

one method would be to use itertools.islice

>>> gen = (x for x in range(10))
>>> index = 5
>>> next(itertools.islice(gen, index, None))
5

Simplest way to get the first n elements of an iterator

Use itertools.islice():

from itertools import islice
print(list(islice(it, 3)))

This will yield the next 3 elements from it, then stop.

Is there a built-in `take(iterable, n)` function in Python3?

itertools.islice does this (and more), without converting to a list or erroring out if not enough elements are produced.

You could write your function in terms of this one cleanly:

def take(iterable, *, n):
li = list(itertools.islice(iterable, n))
if len(li) != n:
raise RuntimeError("too short iterable for take")
return li


Related Topics



Leave a reply



Submit