# Get first N elements from a channel

**URL:** <https://community.seqera.io/t/get-first-n-elements-from-a-channel/125>\
**Category:** Tips & Tricks\
**Tags:** nextflow\
**Created:** [October 2, 2023, 7:44am UTC](https://community.seqera.io/t/get-first-n-elements-from-a-channel/125 "2023-10-02T07:44:13Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mribeirodantas](https://dub1.discourse-cdn.com/flex013/user_avatar/community.seqera.io/mribeirodantas/32/235_2.png) [@mribeirodantas](https://community.seqera.io/u/mribeirodantas)\
**Post date:** [October 2, 2023, 7:44am UTC](https://community.seqera.io/t/get-first-n-elements-from-a-channel/125/1 "2023-10-02T07:44:13Z")

</div>

You may want to consume the first N elements from a channel and don’t know how to do it. Even though there is an operator for that (`take`, check details [here](https://www.nextflow.io/docs/latest/operator.html#take)), I think this is a nice opportunity to try to reproduce its behavior by combining other operators. It’s also important to mention that the `first` channel operator (details [here](https://www.nextflow.io/docs/latest/operator.html#first)) has a different purpose.

Here, we’ll use the `buffer` channel operator (details [here](https://www.nextflow.io/docs/latest/operator.html#buffer)) that splits a channel into subsets of a specific size and then we will use the `first` channel operator to consume this first subset which contains the first N elements from the channel.

```groovy
Channel
  .of(1..100)
  .buffer(size: 5)
  .first()
  .flatten()
  .view()

```

Or

```groovy
Channel
  .of('a'..'z')
  .buffer(size: 5)
  .first()
  .flatten()
  .view()

```

Notice that the `buffer` operator will create subsets of size 5, where each subset is a single element. Then, the `first` operator will consume the first element, which is this subset with 5 items. The `flatten` operator will turn this single element with five items into a channel with five elements. The `view` operator will print the channel to the screen 😃

In case you’re curious, you can find below the output for the last snippet:

```console
N E X T F L O W ~ version 23.09.2-edge
Launching `marcel.nf` [romantic_waddington] DSL2 - revision: c2d9ba8d7b
a
b
c
d
e

```
