Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

With linq I would

var top5 = array.Take(5); 

How to do this with Python?

like image 296
Jader Dias Avatar asked Mar 08 '11 14:03

Jader Dias


People also ask

How do you find the first n elements in a list?

To get the first N elements of a list, use for loop with range(0, N), create a new empty list, and append the elements of source list to new list in the for loop. range(0, N) iterates from 0 to N-1, insteps of 1.

How do you iterate through a generator object?

You need to call next() or loop through the generator object to access the values produced by the generator expression. When there isn't the next value in the generator object, a StopIteration exception is thrown. A for loop can be used to iterate the generator object.

How do you repeat a list of elements?

Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list.

Can you slice a generator?

Iterators and generators can't normally be sliced, because no information is known about their length (and they don't implement indexing). The result of islice() is an iterator that produces the desired slice items, but it does this by consuming and discarding all of the items up to the starting slice index.


2 Answers

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)

like image 173
lunixbochs Avatar answered Sep 28 '22 02:09

lunixbochs


import itertools  top5 = itertools.islice(array, 5) 
like image 42
Jader Dias Avatar answered Sep 28 '22 00:09

Jader Dias