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!’

Python

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

 

JavaScript

Summary

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.

References

  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

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*

code

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