title: Follow a linked list

text:
# Question
Title: Follow a linked list
For this challenge, a linked list looks like this:

```
[1, 2, 4, 0, 6, 1, 3, 1]

```

You'll notice there's no data; each item in the list is just a reference to the index of the next one. Your task is to write a program or function which will follow a linked list like this forever, outputting each item as it is encountered. For example, for the above input:

```
[1, 2, 4, 6, 3, 0, 1, ...]

```

Input and output can be represented in any reasonable manner. All numbers in the input will be valid indices in the list, and you can choose if it's 0- or 1-indexed. The output will be infinite, and as long as your program would *theoretically* give a correct result given infinite time and resources it's valid.

**Test cases:**

Zero indexed, using lists.

```
[0]         -> [0, 0, ...]
[1, 0]      -> [1, 0, 1, ...]
[0, 1, 2]   -> [0, 0, ...]
[2, 1, 0]   -> [2, 0, 2, ...]
[4]         -> (does not need to be handled)

```

# Answer
> 16 votes
# Haskell, 17 bytes

```
f x=iterate(x!!)0

```

0-indexed

Try it online!

# Answer
> 16 votes
# convey, 36 29 bytes

```
v<<<<,{
\~./."
>"`=>!
 >!0<"}

```

Try it online!

`{` gets the input, that will get looped around in the upper two rows, while outputting downwards the length `\`, its indices `/.` and a copy of itself `"`. It will only continue after `~.` (batch) if `n` elements reach `~.`, whereas `n` will be the length.

We then take `!` `n` copies of the current index `i` (starting with 0) and compare `=` them to the indices of the list. This returns either 1 or 0. We take the correspondent element of the copied list so many times, effectively filtering the others out. The next index then gets copied to the output `"}` and waits for the next iteration.

# Answer
> 10 votes
# Husk, 4 bytes

```
¡!¹←

```

Try it online!

1-indexed, returns an infinite list.

## Explanation

```
¡!¹←
   ← take the first element as the start
¡    apply the following infinitely:
 !¹  index into the input

```

# Answer
> 9 votes
# JavaScript (V8), 29 bytes

Zero-indexed. Prints forever. (Where *forever* means *until the call stack overflow*.)

```
f=a=>print(a.i=a[~~a.i])|f(a)

```

Try it online!

### Commented

```
f = a =>       // f is a recursive function taking the input array a[]
  print(       // print:
    a.i =      //   update the current index, which is stored in the
               //   property 'i' of the surrounding object of a[]:
      a[~~a.i] //     it's initially undefined, so we use '~~' to coerce
               //     it to a number (zero) on the first iteration
  )            // end of print()
  | f(a)       // unconditional recursive call

```

The `a.i` trick saves 2 bytes over the more straightforward version:

```
f=(a,i=0)=>print(i=a[i])|f(a,i)

```

Try it online!

# Answer
> 7 votes
# , ~~35~~ 32 bytes

-3 bytes thanks to Giuseppe.

```
function(l)repeat show(T<-l[+T])

```

Try it online!

1-indexed, prints the list indefinitely. A rare use for `show`, which is 1 byte shorter than `print`, and separates the output unlike `cat`.

The variable `T` is initially  `TRUE`; `+T` converts it to the integer `1`, and thereafter it is updated at each step to the relevant list entry.

# Answer
> 7 votes
# Rattle, 11 bytes

```
|IP0[gpP~]0

```

Try it Online!

Update: changing link to new Rattle interpreter (please let me know if there are issues - I couldn't find any issues but this is a newer version of Rattle)

# Explanation

```
|                  takes the user's input
  I                stores the user's input in an array
    P0             sets the pointer to 0
       [ ...... ]0 infinite loop
         g         gets the value at the pointer
           p       prints this value
             P~    sets the pointer to this value

```

# Answer
> 6 votes
# 05AB1E, 4 bytes

```
0[è=

```

0-based indexing.
Prints the numbers newline-delimited to STDOUT indefinitely.

Try it online or verify all test cases, but only printing the first 10 numbers of each.

**Explanation:**

```
0     # Start with index 0
 [    # Loop indefinitely:
  è   #  Use the current integer to index into the (implicit) input-list
   =  #  Print it with trailing newline (without popping, so it'll become the index for
      #  the next iteration)

```

# Answer
> 6 votes
# dc, ~~29~~ 28 bytes

```
[z1-:az0<L]dsLx0[;aplLx]dsLx

```

Try it online!

0-indexed; takes input on the stack (just prepend it). If we assume input is already in `a`, cut off the first 16 bytes. Will perish when the call stack overflows.

```
[ # Phase 1: shove stuff into an array
  z1-  # if there are 7 things on the stack, push 6
  :a   # store whatever was on top into e.g. a[6]
  z0<L # loop while stack isn't empty
]dsLx  # execute immediately and with extreme prejudice

0 # first index to check out
[ # Phase 2: the challenge
  ;a  # push a[tos]
  p   # print it
  lLx # loop forever
]dsLx # autobots, roll out

```

~~I feel like the `0!=` should be reducible to `1>`~~ never mind, I just can't read. Woohoo!

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~12~~ 11 bytes

```
{⍺∇⎕←⍵⌷⍺}∘0

```

Try it online!

0-indexed, takes input as the left argument.

-1 byte from user.

```
{⍺∇⎕←⍵⌷⍺}∘0
{⍺∇⎕←⍵⌷⍺}∘0 take 0 as initial right argument
   ⎕←⍺⌷⍵    print element at right arg
 ⍺∇ ⍵⌷⍺     recursive call with the input and new right arg

```

# Answer
> 5 votes
# Julia 1.0, ~~24~~ 21 bytes

```
>(a,i=1)=a>@show a[i]

```

Try it online!

1-indexed

# Answer
> 5 votes
# Whitespace, 89 bytes

```
[S S S T    N
_Push_1][S N
S _Duplicate_1][S N
S _Duplicate_1][S N
S _Duplicate_1][N
S S N
_Create_Label_READ_INPUT_LOOP][T    N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][N
T   S S N
_If_0_Jump_to_Label_DONE_READING][S S S T   N
_Push_1][T  S S S _Add][S N
S _Duplicate][S N
S _Duplicate][N
S N
N
_Jump_to_Label_READ_INPUT_LOOP][N
S S S N
_Create_Label_DONE_READING][S N
N
_Discard_top][N
S S T   N
_Create_Label_PRINT_LOOP][T T   T   _Retrieve_at_address][S N
S _Duplicate][T N
S T _Print_as_integer][S S S T  S S T   N
_Push_9_tab][T  N
S S _Print_as_character][N
S N
T   N
_Jump_to_Label_PRINT_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

1-based indexing.
Whitespace doesn't have any lists, so we'll read the numbers one at a time from STDIN. Input numbers will end with a trailing `0`, so the program knows when all the numbers are read from STDIN. I.e. test case `[1,2,4,0,6,1,3,1]` would be taken as input `2\n3\n5\n1\n7\n2\n4\n2\n0`.
Outputs the numbers tab-delimited to STDOUT indefinitely.

**Try it online** (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer index = 1
Start READ_INPUT_LOOP:
  Read input as integer from STDIN, and store it in the heap at address `index`
  Integer input = retrieve the input from address `index`
  If(input == 0):
    Jump to DONE_READING
  index = index + 1
  Go to next iteration of READ_INPUT_LOOP

Label DONE_READING:
  Reset index to 1
  Start PRINT_LOOP:
    index = retrieve integer from heap at address `index`
    Print `index` as integer to STDOUT
    Print character '\t'
    Go to next iteration of PRINT_LOOP

```

# Answer
> 5 votes
# Python 3.8 (pre-release), ~~37~~ 34 bytes

```
def f(l,i=0):print(l[i]);f(l,l[i])

```

Try it online!

thanks user for helping save 3 bytes

slightly modified version of 31 bytes, but it prints an extra zero at the beginning

```
def f(l,i=0):print(i);f(l,l[i])

```

Try it online!

# Answer
> 5 votes
# CJam, ~~14~~ 12 bytes

```
q~{_T=:Tp1}g

```

Input is taken from STDIN, 0-based, with format `[1 2 4 0 6 1 3 1]`.

Output is printed to STDOUT, separated by newlines.

**Try it online!** Or verify test cases: **1**, **2**, **3**, **4**.

## How it works

```
q               e# Read input as a string
 ~              e# Evaluate: gives the input as a list of numbers
  {       }g    e# Do...while, popping condition from the stack
         1      e# Push 1 at the end of each iteration, to produce an infinite loop
   _            e# Duplicate the input list
    T           e# Push variable T. This is initially 0
     =          e# Get entry at that index (0-based)
      :T        e# Assign the result to variable T
        p       e# Print with newline

```

# Answer
> 5 votes
# Rust, ~~50~~ 49 bytes

```
|a|(|mut i|loop{i=a[i];println!("{}",i)})(0usize)

```

Try it online!

# Answer
> 4 votes
# PHP, 34 bytes

```
for($i=1;;)echo($i=$argv[$i])."
";

```

1-indexed, because `$argv` contains the script name at index 0, first argument is then `$argv[1]`. Too bad the new line takes a lots of bytes more, without it the brackets around `$i=$argv[$i]` are not necessary..

Try it online!

# Answer
> 4 votes
# Java (JDK), 46 bytes

```
a->{for(int i=0;;)System.out.println(i=a[i]);}

```

Try it online!

# Answer
> 4 votes
# C (gcc), 38 bytes

```
i;f(int*a){printf("%d ",i=a[i]);f(a);}

```

Try it online!

# Answer
> 4 votes
# , 31 bytes

Note that tests don't work, but `print` returns its input so we can recurse. Curiously this is different from `cat` and `show` which return NULL.

```
function(l,i=1)f(l,print(l[i]))

```

Try it online!

# Answer
> 4 votes
# Bash, 51 50 bytes

```
f(){
A=($@)
I=0
while
I=${A[$I]}
do
echo $I
done
}

```

Try it online!

I was disappointed to find I could not use $@ as an array. I had to copy it to A.

The test code limits the output to 20 lines, and wraps it (or tries). Terminates only on signal, like SIGPIPE.

Edit: TIO seems to say I don't need the final newline. -1. Note that all my other newlines could become either spaces or semicolons, but I felt newlines had a better (weirder?) style in this case.

# Answer
> 4 votes
# MATLAB and Octave, 20 bytes 32 bytes

(I've been informed that it is not allowed on this site to assume the input is an array, original answer below the line.)

```
@(x)eval('1,while 1,x(ans),end')

```

Thanks to Luis Mendo for this solution to make a function out of my original answer. It is two bytes shorter than the more obvious solution:

```
function f(x),1,while 1,x(ans),end

```

Try it online!

---

```
1,while 1,x(ans),end

```

1-indexed, the input is in matrix `x`. For example:

```
>> x = [1, 2, 4, 0, 6, 1, 3, 1] + 1;
>> 1,while 1,x(ans),end
ans =
     1
ans =
     2
ans =
     3
ans =
     5
ans =
     7
ans =
     4
ans =
     1
...

```

`ans` is the default variable expression results get assigned to. The code above is equivalent to:

```
ans = 1
while 1
   ans = x(ans)
end

```

The result of the assignment is shown to the command line because statements are not terminated with a semicolon.

# Answer
> 4 votes
# Common Lisp, 44 bytes

### (Function prints in the square bracket + comma style of most languages)

I used Common Lisp's `format` specifiers to handle all the control flow.

```
(defun f(l)(format t"[~{~a~:*~v@*~^, ~}]"l))

```

### Example usage:

```
(defparameter *test* '(1 2 4 0 6 1 3 1))

(f *test*) ; Will print [1, 2, 4, 6, 3, 0, 1, ... and so forth forever.

```

Edit: Technically the ending square bracket would never be reached, so we may omit the closing square bracket in the format string to have a 43 byte solution.

# Answer
> 4 votes
# Python 3, ~~49~~ 37 bytes

Thanks to Jo King for -12 bytes!

```
def f(l,c=0):
 while 1:c=l[c];yield c

```

Try it online!

# Original

```
def f(l):
    c=l[0]
    while 1:c = l[c];yield c

```

Try it online!

This code takes an input, sets c(which holds the index), then continuosly `yield`s c after updating it to the new location. While this isn't the best answer on here, even for python,  ~~I don't think it can really be improved upon without using recursion.~~  Clearly, I was wrong.

# Answer
> 3 votes
## Batch, 94 bytes

```
@set n=0
:g
@call:c %*
@echo %n%
@goto g
:c
@for /l %%i in (1,1,%n%)do @shift
@set n=%1

```

Takes a 0-indexed list of command line arguments (change `=0` to `=1` and `%1` to `%0` for 1-indexing). The `:c` subroutine exists to shift a copy of the command line, thus avoiding destroying the command line. For short lists (up to 9 elements), the following 51-byte 1-indexed script suffices:

```
@set n=1
:g
@call set n=%%%n%
@echo %n%
@goto g

```

# Answer
> 3 votes
# Perl 5 `-a`, 22 bytes

```
$_=$F[$_]while say$_*1

```

Try it online!

Input needs to be space separated.

# Answer
> 3 votes
# Charcoal, 15 bytes

```
≔⁰ηＷ¹«≔§θηηＩηＤ⎚

```

Try it online! Link is to verbose version of code. 0-indexed. Charcoal rate-limits its output, so TIO will probably time out rather than fill its output buffer. Explanation:

```
≔⁰η

```

Start at index 0.

```
Ｗ¹«

```

Repeat forever.

```
≔§θηη

```

Update the index.

```
ＩηＤ⎚

```

Output the index, clearing the canvas for the next loop.

# Answer
> 3 votes
# Ruby, ~~27~~ 23 bytes

*Saved a whooping 4 bytes, thanks to Dingus!!*

```
f=->a,i=0{f[a,p(a[i])]}

```

Try it online!

---

# Ruby, 23 bytes

*As suggested by Dingus, here is another way, and it prevents the "stack overflow" error!!*

```
->a,i=0{loop{p i=a[i]}}

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 39 bytes

```
(,)*(((?<-1>,)|\d+)+.*)
$3$*,$2,
}*`\G,

```

Try it online! 0-indexed. Explanation: The current index is encoded in unary as the number of leading `,`s.

```
(,)*(((?<-1>,)|\d+)+.*)

```

Match the current index, then as many commas and integers as possible, but only matching as many commas as the current index. The last submatch is therefore the next index.

```
$3$*,$2,

```

Replace the current index with the submatch in unary, then append the original input and an extra comma to ensure that the buffer changes each time (since Retina 0.8.2 doesn't have truly infinite loops).

```
}`

```

Repeat until the buffer stops changing, which it won't because we append a comma to the end on each loop.

```
*`\G,

```

Convert the current index to decimal and print it.

# Answer
> 3 votes
# k4, ~~17~~ 13 bytes

```
{0W(0N!x@)/0}

```

Loops "infinitely" via `0W`, outputting (`0N!`) the index in question. Begins with the first value in the input, i.e. `x 0`.

# Answer
> 3 votes
# JQ, 37 bytes

```
[0,.]|recurse([.[1][.[0]],.[1]])|.[0]

```

Try it online!

# Answer
> 3 votes
# FALSE, 65 24 21 bytes

```
[c;[1_][ø$.32,c;\-]#]

```

Try it online! Assumes that array is already pushed onto stack and len(array)-1 is stored in c.

-41 because Razetime pointed out that I could just submit a function instead.

-3 because of removed redundancy.

## Explanation

```
[c; {Push len(array) on stack for index 0}
[1_] {Value for true}
[ø {Get value at current index}
$. {Dup and print int}
32, {Print space}
c;\- {Subtract c by this new value to get new index}
]#] {Do lambda 2 while lambda 1 outputs true (forever)}

```

# Answer
> 3 votes
# x86 machine code, 6 bytes

Binary:

```
00000000: 33c0 d7aa ebfc                           3.....

```

Listing:

```
33 C0       XOR  AX, AX         ; AL = 0
        L1:
D7          XLAT                ; AL = [BX+AL]
AA          STOSB               ; [DI++] = AL
EB FC       JMP  L1             ; loop infinitely

```

Input array (0 indexed) at `[BX]`, output to array at `[ES:DI]`.

Run with DOS DEBUG:

# Answer
> 3 votes
# Bash, 39 37 bytes

```
f()(x=${x-1}
echo ${!x}
x=${!x}
f $@)

```

Try it online!

-2 thanks to "tail spark rabbit ear"

One-based indexing.

* The bash indirection operator `${!v}` returns the value of the variable whose name is `$v`
* Function arguments are named `$1`, `$2`, etc.
* These two features, along with recursion and a default value of 1 `x=${x-1}` are all we need. The current index is stored in `$x` and the input array is the function arguments.

# Answer
> 3 votes
# Phooey, 35 bytes

```
(>2&.)(<2)@1(1>(>2&-1@)<$i" "@(<2))

```

Try it online!

Input is one-indexed space separated integers followed by a zero.

The output is a list of space separated integers to stdout.

Today, I learned something *"interesting"* about Phooey.

If you looked at my other post, I mentioned the `!` modifier, which makes any instruction use the value from the stack.

I figured, okay, I could do something like this, using the stack modifier to do a variable offset. Easy.

```
...>@<(1>!@$i" "(<))

```

It turns out that it wasn't entirely true.

```
    else if(op.payload_type == PayloadType::SPECIAL) {
        switch(op.payload.special) {
            // snip
            case SpecialPayload::STACK:
                op.payload_type = PayloadType::NORMAL;
                op.payload.normal = pop();
                return op.payload.normal;
            // Snip
        }
    }

```

While the user input variants don't do this, for some dumb reason, using the `!` operator will only work once: after that, it will be constant.

So therefore, I had to do this manually.

```
(>2&.)(<2)@1(1>(>2&-1@)<$i" "@(<2))

# do
(
    # We write into every other cell, as we
    # need a temp buffer for indexing.

    # Additionally, we need a null terminator to
    # mark the start of the list.
    >2
    # Read integer into tape
    &.
    # Loop until the user enters a zero.
    #
    # This could be made easier if the developer
    # initialized their variables to zero:
    #   int64_t read_int(std::istream& stream) {
    #       int64_t res; // <= uninitialized
    #       stream >> res;
    #       return res;
    #   }
    # but no, this is a terribly coded esolang.
    # Instead, we either have to do ~i or require
    # a sentinel.
# while (*cell)
)
# Scan back to the beginning with another do-while.
# Again, we are writing every two cells.
(<2)
# Push the first index to the stack.
@1
# do
(1
    # move to a scratch cell
    >
    # move to the cell position
    #   do { ptr++; } while (--n);
    # do
    (
        # go to the next scratch cell
        >2
        # pop into the scratch cell
        &
        # subtract 1
        -1
        # push back
        @
    # while index is not zero
    )
    # BUG: we have a memory leak here: we leave the last
    # index on the stack cuz it's PPCG and we dgaf about that
    # To fix it, add an ampersand here.
    #   &

    # Move backwards to the numerical index
    <
    # print the integer and a space
    $i" "
    # push the new index
    @
    # scan back to the beginning
    (<2)
# loop forever
# while (1)
)

```

Animated version with the memory leak fixed (which I totally didn't create manually using raw ANSI escape codes in a Phooey file):

# Answer
> 3 votes
# Factor, ~~33~~ 30 bytes

Saved 3 bytes thanks to @Bubbler

```
[ 0 [ over nth 2dup . ] loop ]

```

Try it online!

```
[ 0 [ over nth 2dup . ] loop ]
  0                            ! Push the start index
                        loop   ! Repeatedly do:
      over                     ! Bring the list to the top
           nth                 ! Get the element at the current index
                2dup           ! Duplicate the list and the index
                     .         ! Print and discard the copy of the index
                               ! The copy of the list is used as a truthy value
                               ! to keep the loop going

```

# Answer
> 3 votes
# Vim, 15 bytes

```
YPqq@"Y`.p@qq@q

```

Try it online! (slightly modified version to loop 99 times instead of indefinitely, the result wouldn't show on TIO otherwise)

Language of the month! I'm learning to work with Vim thanks to that :D

This takes 1-based indices each on a separate line, and output is the sequence of indices visited (also one per line) followed by the original list... Fortunately, since we are assuming this will be running for infinite time we will never see that final part.

### Explanation

```
YPqq@"Y`.p@qq@q
YP                 Duplicate the first line (to write the first index)
  qq        q      Record macro q (kind of like a recursive function)
    @"               Jump down a number of lines equal to the last copied number
      Y              Copy the number at that line
       `.            Jump back to where we did our last change
         p           Write the copied number after that
          @q         Call macro q recursively
             @q    Call macro q and start the infinite loop

```

I found out how to use `@"` by accident: it is supposed to run the last copied text as a macro. Since with `Y` we are copying a full line (newline terminated), the macro will be `n<CR>`, meaning a number followed by enter, which has the effect of going to the next line for `n` times.

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~28~~ 27 bytes

```
1//.i_:>0Print[a=#[[i]]]+a&

```

Try it online!

1-indexed. Prints each item on its own line.

### 20 bytes

```
1//.i_:>Echo@#[[i]]&

```

Try it online!

Precedes each line with `>>` .

---

By default, `//.` only does up to 65536 iterations.

### 29 bytes

```
For[i=1,1>0,Print[i=#[[i]]]]&

```

Try it online!

# Answer
> 2 votes
# SmileBASIC 4, 33 bytes

```
DIM C=COPY(L)@_?C[SHIFT(L)]GOTO@_

```

---

```
DIM C=COPY(L)  'L[] is the infinite input stack, C[] is a separate copy.
?C[SHIFT(L)]  'Remove the 0th element from the infinite stack, print the value corresponding to that 0th element from the copy.
GOTO@_  'Return the pointer to the label @_ and repeat forever.

```

# Answer
> 2 votes
# Vyxal, 4 bytes

```
0{i…

```

Try it Online!

Note that the `-5` flag is purely for code time-out purposes: it makes the online interpreter stop execution if it takes longer than 5 seconds.

## Explained

```
0{i…
0       # Push 0 to the stack
 {      # Repeat the following infinitely:
  i     #   Push the item at index (top of stack) in the input
   …    #   Print that without popping

```

# Answer
> 2 votes
# Zsh, 23 bytes

```
echo $i
i=$@[++i] $0 $@

```

Try it online!

The `++i` is necessary because Zsh is 1-indexed and by default parameters are 0 in arithmetic mode.

# Answer
> 2 votes
# PowerShell Core, ~~27~~ 22 bytes

```
for(){($i=$args[+$i])}

```

-5 bytes thanks to mazzy!

Try it online!

0 indexed, takes the list as an array as parameters and outputs the result list on the standard output

# Answer
> 2 votes
# Pyth, 7 bytes

```
#=Z
@QZ

```

Try it online!

Takes a 0-indexed list as input, prints each term on a new line until an error is thrown.

# Answer
> 2 votes
# Python, ~~84~~ 61 bytes

```
s=input()
i=s.split(" ")
n=0
o=[]
while True:
o.append(i[n])
n=i[n]

```

Short, sweet, and simple: takes the input list, finds the index, adds the number to the list\<s, and repeat. (With thanks to Redwolf for the edits)

# Answer
> 2 votes
# Fig 0.1.0, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
(,iQ

```

See the README to see how to run this

I cannot believe I saw the Vyxal answer and did not think of porting it.

```
(,iQ - Takes input like "[1,0]"
(    - Repeat forever
 ,   - Print
  iQ - The item at the last index obtained

```

# Answer
> 2 votes
# \>\<\>, 55 bytes

```
i:0(?v
v&0{~<
<~v?:  -1r<r%-1l+l$&:$-&:oan:
  >rl1-[}]^

```

Try it

## Explanation

Since fish has no concept of a "array" I had to get a bit creative. Keeps the current index in the register, then subtract it from the number. Shift the stack left that many times (since the stack is reversed)

~~I just want the hat.~~

# Answer
> 1 votes
# x86 32-bit machine code (Linux), 25 bytes

```
00000000: 9631 c08b 0486 5068 1500 0000 93e8 fcff  .1....Ph........
00000010: ffff 93eb ee25 7520 00                   .....%u .

```

Assembly (NASM):

```
section .text
extern printf
global func
func:				; Arg passed in EAX (regparm conv.)
	xchg esi, eax		; ESI=base ptr
	xor eax, eax		; EAX=offset, starts at 0
	loop:
		mov eax, [esi + 4*eax]	; Load offset with next LL item (4x bc each item is 32 bits wide)
		push eax
		push fmt
		xchg eax, ebx	; Store EAX contents before printf call
		call printf	; Print
		xchg ebx, eax	; Retrieve EAX contents
		jmp loop	; Loop forever
				; Ret isn't needed as we don't return
fmt: db '%u ',0x00

```

Try it online!

# Answer
> 1 votes
# Pip, 7 bytes

```
W1YPg@y

```

Zero-indexed. Takes the input list as separate command-line arguments. Attempt This Online!

### Explanation

```
W1       ; While 1 (loop forever):
    g    ;   The argument list
     @y  ;   Get the item at index y
  YP     ;   Print that value and assign it to y

```

The initial value of `y` is `""`, which acts as `0` in a numeric context.

# Answer
> 1 votes
# APL (Dyalog Unicode), 24 bytes

Much longer than the other APL answer, but I just wanted to use matrix-vector multiplication instead of indexing.

```
⊢(∘.=∨.∧⍣{≡⎕←⊃⍸⍺}0=⊢)⍳∘≢

```

Try it online!

# Answer
> 1 votes
# Fig, commit 41637b2, \\$6\log\_{256}(96)\approx\\$ 4.939 bytes

```
G0'i#!

```

To run this, download the source and then run in the root directory:

```
./gradlew run --args="code.txt <args>"

```

Explanation:

```
G0'i#! - Takes input like "[1,0]"
G      - Generate an infinite list using...
 0     - 0 as the initial value...
  '    - And using the generator function...
   i   - Index into
    #! - The program's input
       - Using the last index generated

```

# Answer
> 1 votes
# Go, 60 bytes

```
import."fmt"
func f(L[]int){for i:=L[0];;i=L[i]{Println(i)}}

```

Attempt This Online!

This one prints each step.

### Go, 65 bytes, invalid

```
func f(L[]int)(P[]int){for i:=L[0];;i=L[i]{P=append(P,i)}
return}

```

Attempt This Online!

It's an infinite loop, but the path it takes is stored in `P`.

# Answer
> 1 votes
# Raku, 21 bytes

```
{$^a[0],{$a[$_]}...*}

```

Try it online!

Anonymous function that takes an array and returns an infinite sequence

# Answer
> 0 votes
# 05AB1E, 4 bytes

*Ties Kevin Cruijssen's 05AB1E answer, Razetime's Husk answer, and Lyxal's Vyxal answer for #1.*

```
н[=è

```

Try it online!

```
н[=è  # full program
н     # push first element of...
      # implicit input
 [    # forever...
  =   # output top of stack
   è  # element in...
      # implicit input...
   è  # at index top of stack
      # (implicit) exit loop

```

Do I get extra points for the `[=`? :P

---
Tags: code-golf, data-structures
---