Take the first 3, last 2, and skip the first 2 items from a list.

← Streams and Pipelines · Ref: Q1138

head takes first N, tail takes last N, skip drops first N:

  cat items | head 3 > stdout
  cat items | tail 2 > stdout
  cat items | skip 2 > stdout

Combine them: cat items | skip 1 | head 3 > stdout. See Q931.

Example

defines module qa.streams.streamheadtailskip

  defines program

    StreamHeadTailSkipDemo()
      stdout <- Stdout()

      items <- [10, 20, 30, 40, 50]

      stdout.println("Head 3:")
      cat items | head 3 > stdout

      stdout.println("Tail 2:")
      cat items | tail 2 > stdout

      stdout.println("Skip 2:")
      cat items | skip 2 > stdout

      stdout.println("Skip 1 then Head 3:")
      cat items | skip 1 | head 3 > stdout

Common mistakes

E50060 — EK9 uses 'head N' not limit(). Similarly 'tail N' and 'skip N'.

Incorrect:

      cat items | limit(3) > stdout

Correct:

      cat items | head 3 > stdout
Other ways to ask this
  • I need to slice a stream: first N, last N, or drop the first N items
  • In Python I'd use list[:3], list[-2:], list[2:]. Write the EK9 equivalents
  • Given [10,20,30,40,50], demonstrate head, tail, and skip operations
  • Paginate a stream by taking or skipping a fixed number of items

Coming from another language?

Java: stream().limit(3), stream().skip(2). Python: list[:3], list[2:]. Rust: .take(3), .skip(2). EK9: | head 3, | skip 2, | tail 2.

Keywords: slice, first, last, take, paginate, skip, head, tail