Skip to main content
1 of 3
kirma
  • 19.1k
  • 1
  • 55
  • 95

Clean way to conceptually extract Parts from a circular list

I quite often run into a situation where I want to treat a list as a circular (repeating) one, and want to take a specific sublist of it, such as...

One past the end of the list:

Append[#, First@#] & @ {a, b, c}

{a, b, c, a}

An item preceding the list included:

Prepend[#, Last@#] & @ {a, b, c}

{c, a, b, c}

Three rounds of the circular list from the start:

Join[#, #, #] & @ {a, b, c}

{a, b, c, a, b, c, a, b, c}

Or even every second item on the list, for two rounds:

Join[#, #][[;; ;; 2]] & @ {a, b, c}

{a, c, b}

Obviously there are more of these where you can combine extended features of Part (the [[ ... ]] syntax) over circular lists.

What would be the most practical (short, clean, efficient, maybe even elegant) ways to do this, without writing one-off code every time such a small need arises?

kirma
  • 19.1k
  • 1
  • 55
  • 95