Accueil / Informatique / Data Structures / Fastest way to get the first n elements of a List into an Array

Fastest way to get the first n elements of a List into an Array

Print Friendly, PDF & Email

def s = ‘Hello Groovy world!’
assert s.take(5) == ‘Hello’
assert s.drop(6) == ‘Groovy world!’


Let’s assume an arbitrary list/array:

in_list = list(range(10))
// Python2: in_list = range(10)
// in_array = [i for i in range(10)]

Slicing the list

n = 5
top5 = in_list[: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




From my perspective, this operation is often requested in real applications. Beware of existing solutions is probably useful and necessary because we could need either of them in your coming projects.


  1. Fastest way to get the first n elements of a List into an Array, accessed on 20/05/2020
  2. Groovy Goodness: Take and Drop Items from a List, accessed on 20/05/2020
  3. How to take the first N items from a generator or list in Python?, accessed on 28/05/2020

À propos Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via if you want to talk about information technology, education, and research on complex networks analysis (i.e., metabolic networks analysis), data analysis, and applications of graph theory. Specialties: researching and proposing innovative business approaches to organizations, evaluating and consulting about usability engineering, training and employee development, web technologies, software architecture.

Laisser une réponse

Votre adresse email ne sera pas publiéeLes champs requis sont surlignés *




Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.