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

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.