# Split list

**URL:** <https://swi-prolog.discourse.group/t/split-list/4836>\
**Category:** Help!\
**Tags:** list\
**Created:** [January 3, 2022, 6:39pm UTC](https://swi-prolog.discourse.group/t/split-list/4836 "2022-01-03T18:39:06Z")\
**Posts on this page:** 1\
**Showing post:** 16

<div class="post-metadata">

**Author:** ![Boris](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/boris/32/7486_2.png) [@Boris](https://swi-prolog.discourse.group/u/Boris)\
**Post date:** [April 16, 2022, 1:36pm UTC](https://swi-prolog.discourse.group/t/split-list/4836/16 "2022-04-16T13:36:14Z")

</div>

You could take advantage of the _Rest_ argument of phrase/3; and there is also sequence//2 from library(dcg/high\_order). It would be enough to define:

```prolog
length_list(N, L) -->
    { length(L, N) },
    L. % yes don't need string//1

```

Then:

```prolog
?- use_module(library(dcg/high_order)).
true.

?- phrase(sequence(length_list(2), Sublists), [a,b,c,d], Rest), !.
Sublists = [[a, b], [c, d]],
Rest = [].

?- phrase(sequence(length_list(2), Sublists), [a,b,c,d,e], Rest), !.
Sublists = [[a, b], [c, d]],
Rest = [e].

```

But of course it all depends on the use case.

EDIT: since there are some “likes” on this, I would like to point out two issues.

1. As it stands, using `L` instead of `string(L)` is indeed a bit slower.
2. Since sequence//2 leaves choice points, it will eventually run out of memory if the list we are parsing is long enough. Cutting on every matched prefix will avoid this.

---

_[View the full topic](https://swi-prolog.discourse.group/t/split-list/4836)._
