Home / Khoa học Máy tính / 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!’

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

About Nguyen Vu Ngoc Tung

I love making new professional acquaintances. Don't hesitate to contact me via nguyenvungoctung@gmail.com 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.

Leave a Reply

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

*

*

code

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