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


Question

With I would

var top5 = array.Take(5);

How to do this with Python?

1
264
10/1/2015 11:48:34 AM

Accepted Answer

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)

419
6/11/2016 4:17:57 AM

import itertools

top5 = itertools.islice(array, 5)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon