[Question]
  [
Say I have a ragged list, like:
```
[
  [1, 2],
  [3, 
    [4, 5]
  ]
]
```
And I want to iterate over each item and delete it one-by-one. However, I don't know the structure of the list.
So, I have to iterate over the list, with the following algorithm:
* Look at the first item of the list.
* If it's a list, concatenate it to the start of the rest of the list.
* Else, delete it.
For example, with the above example `[[1, 2], [3, [4, 5]]]`:
* `[1, 2]` is a list. Concatenate it - `[1, 2, [3, [4, 5]]]`
* `1` is a number. Delete it - `[2, [3, [4, 5]]]`
* `2` is a number. Delete it - `[[3, [4, 5]]]`
* `[3, [4, 5]]` is a list. Concatenate it - `[3, [4, 5]]`
* `3` is a number. Delete it - `[[4, 5]]`
* `[4, 5]` is a list. Concatenate it - `[4, 5]`
* `4` is a number. Delete it - `[5]`
* `5` is a number. Delete it - `[]`
There are no more items left, so our work is done.
Your challenge is to compute the sizes of the lists resulting from applying this. For example, with the above, the list starts with length 2. It then goes to lengths 3, 2, 1, 2, 1, 2, 1, 0.
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply - that is, you may take a list \$l\$ and generate all terms, or take a list \$l\$ and a number \$n\$ and calculate the nth or first n terms. Your results may or may not contain the length of the initial list at the start, and the 0 at the end, and you may take \$n\$ 0-indexed or 1-indexed.
Since only the shape of \$l\$ matters, you may take it filled with any consistent value instead of arbitrary integers.
\$l\$ may contain empty lists. In this case, it's concatenated as normal and the length decreases by 1.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
## Testcases
These include the leading length but not the trailing 0. [Reference implementation](https://tio.run/##VY7BCgIxDETv/Yo5bnER19WL4JeUIsJm2UKopY3Ifn1Ne9JDSHjJzCTtsr3iXOtCK4JQfizEJDRwsTcDplhwh/MGny0wgYvSjo/PlCgug87t2CoOK2RPTetO3iIUcCjSBKpTm85xaH26qSWIC/2tO84k7xx7iDEphyjD72fOTSPOfoSbtS4jrt57a2v9Ag)
```
[[1, 2], [3, [4, 5]]] -> [2, 3, 2, 1, 2, 1, 2, 1]
[[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]] -> [3, 5, 4, 3, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1]
[3, 4, 5] -> [3, 2, 1]
[[[[[[[[1]]]]]]]] -> [1, 1, 1, 1, 1, 1, 1, 1]
[] -> []
[1, [], 1] -> [3, 2, 1]
[[],[[[]]],[]] -> [3, 2, 2, 2, 1]
```
  
[Answer]
# [R](https://www.r-project.org), ~~62~~ 61 bytes
*Edit: -1 byte thanks to pajonk*
```
f=\(l)if(h<-length(l))c(h,f(c(if(is.list(g<-el(l)))g,l[-1])))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN23TbGM0cjQz0zQybHRzUvPSSzKAXM1kjQydNI1kDaB4ZrFeTmZxiUa6jW5qDkhOM10nJ1rXMBbIghqSkmMLVgImDHWMNHXALGMIZaJjClTKVVxSBNTNlQYikNVDFSMJaEKFUDVB7II5HAA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~27~~ 25 bytes
Anonymous prefix lambda.
```
{√ó‚éï‚Üê‚â¢‚çµ:‚àá((0‚â†‚â°‚äÉ‚çµ)/‚äÉ‚çµ),1‚Üì‚çµ}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ed9Ux@1TXjUuehR71arRx3tGhoGjzoXPOpc@KirGSikqQ@ldQwftU0GMmr/pwHVazzq7QNLrHnUu@XQeuNHbROBBgUHOQPJEA/PYM1qqLm9W3XUFR61TQIS3S0KQEGvYH8/iDHq0dGGOgpGsToK0cZAbKKjYBobG6vOBZIw01EAiRmCKZNYoBqgdLQRmGsJZJnqKJjBFBuDJU2hOiHAMBYKwIIQEmhYNNAgw1h1AA "APL (Dyalog Unicode) ‚Äì Try It Online")
`{`‚Ä¶`}`‚ÄÉ"dfn"; argument is `‚çµ`:
‚ÄÉ`‚â¢‚çµ`‚ÄÉtally the argument
‚ÄÉ`‚éï‚Üê`‚ÄÉprint that
‚ÄÉ`√ó`‚ÄÉsignum of that
‚ÄÉ`:`‚ÄÉif 1 (i.e. there's content):
‚ÄÉ‚ÄÉ`1‚Üì‚çµ`‚ÄÉdrop the first element of the argument
‚ÄÉ‚ÄÉ`(`‚Ä¶`),`‚ÄÉprepend:
‚ÄÉ‚ÄÉ‚ÄÉ`‚äÉ‚çµ`‚ÄÉthe first element of the argument
‚ÄÉ‚ÄÉ‚ÄÉ`(`‚Ä¶`)/`‚ÄÉreplicated by (i.e. if the following holds true):
‚ÄÉ‚ÄÉ‚ÄÉ‚ÄÉ`‚äÉ‚çµ`‚ÄÉthe first element of the argument
‚ÄÉ‚ÄÉ‚ÄÉ‚ÄÉ`0‚â†‚â°`‚ÄÉis its depth different from zero? (i.e. a list)
‚ÄÉ‚ÄÉ`‚àá`‚ÄÉrecurse
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
def f(x,*r):print-~len(r);x>{}<f(*x+r);f(*r)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENXMzVZpD80ikvvIdqgILWECCmiF3HTjXgaD-BtnPQjOEPyZvLeG5I8Xk3rDuc67brnxRk5_4h9ZcCgF4kl3dhj7eT9VNVoaenX19vKYOJn3DBaGj3v4NlgsiUdgbOtNqGOoPK7qnFaQQT9pFhKGUcsRFQCUhKAGa9cQEEcA1MKCIeqh5xYxDymfbvgqhBQ_tRZzxaTdwgl6D8HdgQejDxUTZ5wi7CHZIbGR00f8gU)
Prints to STDOUT; terminates with an error.
# [Whython](https://github.com/pxeger/whython), 37 bytes
-7 bytes thanks to @ovs
```
def f(x,*r):print(len(r)+1);f(*x+r?r)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENBmGnTRfpD48Kd9xBNqCC1hIjtWdx0I97Gvbdx0rSCM0zm8948kjxe92ZwzbUdx-fNmWz9WZ20AYO9SCypzp5bhxfdoqVU0tZg0qd2Z2kmvz15j8mBVATODsr4OgLdH3XnlIwgKMRZlsUUMRNRCshJABYcpYCK2AJSC_BDOaWSmMQ45lO74aoSUP_YxYRWy24wKejfAzonFkYWlcuOv4U_vTNC86uWr_gC)
Despite being Whython, this still also terminates with an error.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~¬†55 53¬†~~ 52 bytes
*Saved 2 bytes thanks to [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)*  
*Saved 1 more byte thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) and [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)*
```
f=a=>[n=a.length,...n?f(a.shift().concat?.(a)??a):a]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZBLDsIgEIb3noIlJDgJfUVNkIMQFqSW1qSBRfE0brrQQ3kFT-HQ1o0yCc_5_p8Z7g8fLt08P2_R7Q-vykkrz9pLC2Pn-zhwAPDKUQvTcHWRMmiDb21UQC1TyrKTNZv2jZkpjB2MoaeOai04KQwnusRRcVIbYxjb_VINJwkQy1IZFCCri-V4xF3NSZNVlgtZ5zzXEGaLfyJzhQVofFzk_FIXOKfidLJbO_7-2gc)
### Commented
```
f = a =>           // f is a recursive function taking the input list a[]
[                  // build the output:
  n = a.length,    //   append the length of a[] and save it in n
  ...n ?           //   if a[] is not empty:
    f(             //     do a recursive call:
      a.shift()    //       extract the leading entry and attempt to
      .concat?.(a) //       concatenate it with the remaining entries
      ??a          //       if it fails, just append a[] (the leading entry
                   //       was not an array)
    )              //     end of recursive call
  :                //   else:
    a              //     stop the recursion and return a[] (which is empty)
]                  // end of output
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒîDg,ƒáDi\√´√¨
```
A byte is saved by taking the input filled with `1`s instead of positive integers.  
Outputs the lengths on separated newlines to STDOUT, including a trailing 0.
[Try it online](https://tio.run/##yy9OTMpM/f//3BSXdJ0j7S6ZMYdXH17z/390tKGOYawOkAQzYmMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2nLpeRfWgLh6fw/N8UlXedIu0tKZszh1YfX/K@tPbTN/n90dLShjmGsDpAEM2JjdRTAQmAuSADORFIAkQKphACQMBgAhSDyQAqqAGg21FQgKxrMBhEA).
**Explanation:**
```
Œî      # Loop until the result no longer changes (e.g. until the list is empty):
 D     #  Duplicate the current list
  g    #  Pop and push the length
   ,   #  Pop and output this length with trailing newline to STDOUT
 ƒá     #  Extract head; pop and push remainder-list and first item separately
  D    #  Duplicate this extracted head
   i   #  If it's a 1:
    \  #   Discard it from the stack
   √´   #  Else (it's a list instead)
    √¨  #   Prepend-merge it to the remainder-list
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes
```
#'{$[t~*t:*x;!0;t],1_x}\
```
[Try it online!](https://ngn.codeberg.page/k#eJxdT+1ugzAM/J+ncLVJgyoUEhK0EmkvkkUroqFFZWUr2UQ1tc8+89WxOtg4d76zUqQPTz+P2l2XLl22ahEpZyh7ay+vhLgUmfP1lBYA0KpNfVDepsjKSrXqrE6+uRCnPQZcebESIH1fcYiBA7tlZLoRL1GxYkgJXwnlcbytlYQEBTFIEDDVTiJmFr0cZSBV/AfQMRh6/j89jW+gw17WvYf5c63XsZiLaIBHgoRk79xHk4ZhXm/trq6KVeOy/GDbfJ8dd3aV1+/h55dtXFkfm5CL5yTiYensKXPlt63OwdZW1tkgC6qycYRozShwQ0HHmIKCNMZA8AKaU0AIK5tXg4qkZzoh/oRBMerG+TV2kkIyuSAke37eDHbibgFaxz0qb9Jp4xDMjNHTrBfefzg90NjgXZsOu7czFN3Qh2oz5/g0QX4BSgWRIw==)
Output includes the length of the initial list and a 0 at the end.
* `{...}\` set up a scan-converge, seeded with the (implicit) input and run until two successive iterations return the same result
	+ `$[t~*t:*x;!0;t]` using `$[c;t;f] cond`, check if the first item is a list or an atom. if it is an atom, return an empty list (`!0`); if it is a list, return the first element of that list
	+ `,1_x` append the remainder of the list (dropping the first item)
* `#'` return the number of items in each iteration
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
√ñ‚î¨‚òª‚ï™<√¶¬∑√´97‚ïûœÜ¬∫‚ô†B
```
[Run and debug it](https://staxlang.xyz/#p=99c202d83c91fa893937c6eda70642&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2)
# [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
√º‚ïú‚ÜêŒ¶‚ñ†Yxbo‚ïü‚Åø‚ñÄ√≠‚ñºŒµ~
```
[Run and debug it](https://staxlang.xyz/#p=81bd1be8fe5978626fc7fcdfa11fee7e&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2)
a generator.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes
```
Print[i+=Length@#-1]#0/@#&[i=1;#]&
```
[Try it online!](https://tio.run/##JYwxC8IwEIX3/o1ABz3Rq2mhSCCLm4PgWDqE0NoMjSDZjvSvx6cO9917d@9udWmZVpeCd2U25f4OMQ1hb25TfKbFqgOP6nS0qh6C4Ysa6zLb3dUvr@3hXdykEmFqMsmZRFObcyaMOoJlQMNrkgayJ2mp@wewQBbiW0xo/LvDHwARoMrlAw "Wolfram Language (Mathematica) ‚Äì Try It Online")
Prints the lengths. Includes a trailing `0`.
```
Print[i+=Length@#-1]#0/@#&[i=1;#]&
                          [i=1;#]   initialize i=1 before run
                    #0/@#           in depth-first, prefix order:
      i+=Length@#-1                   add length-1 to i (atoms have length 0)
Print[             ]                  print i
```
[Answer]
# JavaScript (ES2019), ~~51~~ ~~48~~ 47 bytes
```
i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN_UzbQ2s02w1ymyjYzVt7aIztW3L9HJS89JLMnQVFTN19PT0yvTSchJLfBMLNNI0YyHabjGqJ-fnFZcolCrYKpTmpaSmZealpnCBxPJzUvVy8tM10jSio0t1FEpjdRRANIQdCyI0NYlQiEsVVAHMMAQXn06YDixmQgBIGxhgqsBuXDQun4B8ASRBjosGGQcJL1hwAwA)
Input requires `undefined` as leaves. Output includes initial size and trailing `0`.
I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then there is this 40-byte solution:
```
i=0;f=(v=[])=>[i+=v.length-!!i,v.map(f)]
```
## Algorithm
Instead of implementing the specified process and constructing the intermediate arrays, this submission uses an analytical solution to calculate the output.
Notice that, with the process in the question, each item of the root array is completely deleted before moving on to the next item. Using the original example `[[1,2],[3,[4,5]]`, the `[1,2]` subarray is fully deleted before `[3,[4,5]]` is touched. This means that while processing `[1,2]`, the sizes of the intermediate arrays at each step is the same as those while processing `[1,2]` as a root, but plus 1 because we have to count `[3,[4,5]]`
```
[[1, 2], [3, [4, 5]]]
[1, 2, [3, [4, 5]]]   (size: 3)        |        [1,2]   (size: 2)
[2, [3, [4, 5]]]      (size: 2)        |        [2]     (size: 1)
[[3, [4, 5]]]         (size: 1)        |        []      (size: 0)
```
Take another example from the test cases
```
[[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]]
[6, 3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]]   (size: 5)        |        [6, 3, [1, 3, 4]] (size: 3)
[3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]]      (size: 4)        |        [3, [1, 3, 4]]    (size: 2)
[[1, 3, 4], 4, [2, 3, 9, [5, 6]]]         (size: 3)        |        [[1, 3, 4]]       (size: 1)
[1, 3, 4, 4, [2, 3, 9, [5, 6]]]           (size: 5)        |        [1, 3, 4]         (size: 3)
[3, 4, 4, [2, 3, 9, [5, 6]]]              (size: 4)        |        [3, 4]            (size: 2)
[4, 4, [2, 3, 9, [5, 6]]]                 (size: 3)        |        [4]               (size: 1)
[4, [2, 3, 9, [5, 6]]]                    (size: 2)        |        []                (size: 0)
```
The size difference is 2 here because there are 2 items after the item being processed (`[6, 3, [1, 3, 4]]`).
This shows that this problem can be solved with a recursive algorithm
```
f([1, 2]) = [2, 1, 0]
f([3, [4, 5]]) = [2, 1, 2, 1, 0]
                                [2, 1, 0][2, 1, 2, 1, 0]
                           + [2,       1,             0]
                           --------------------------------
f([[1, 2], [3, [4, 5]]]) =   [2, 3, 2, 1, 2, 1, 2, 1, 0]
```
More precisely, the output of processing an array consists of:
* The initial length of the array, then
* For each item, the result of processing that item, plus adding the number of items after it to each element.
### Naive, readable implementation
```
function f(value) {
    if (value !== undefined) {
        return [
            value.length,
            ...value.flatMap((item, index) => f(item).map((n) => n + value.length - index - 1))
        ]
    }
    return [0]
}
```
## Golfing
First, of course, is to apply basic golfing techniques
```
// 70 bytes
f=v=>v?[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))]:[0]
```
Then, since leaves are `undefined`, we can actually use default argument to treat leaves as `[]` and merge the two branches
```
// 69 bytes
f=(v=[])=>[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))]
```
Then, instead of mapping a second time to add the "base" value `v.length-j-1`, we can make `f` accept a second argument for a value to add to everything.
```
// 67 bytes
f=(v=[],i=0)=>[v.length+i,...v.flatMap((u,j)=>f(u,v.length+i-j-1))]
```
Next, we can pull `i` up to the global scope and mutate it instead of passing it around and using a lengthy expression to calculate the base
```
// 53 bytes
i=0;f=(v=[])=>[i+=v.length,...v.flatMap(u=>f(u,i--))]
```
Finally, we can move the `i--` decrement into `f` so that, instead of decrementing at each `flatMap` iteration, we just decrement `i` at the start of `f`.
```
// 45 bytes
i=1;f=(v=[])=>[i+=v.length-1,...v.flatMap(f)]
```
**BUT**, this breaks because the global variable `i` is changed after calling `f`, which is [forbiddened](https://codegolf.meta.stackexchange.com/a/4940/6972). Specifically, `i` is decremented by 1 for each root call to `f`. Before the change, `i` is decremented by 1 by one per child while looping in `flatMap`, but now `i` is decremented by 1 per call (i.e. per node), and the root is the only node that is not a child.
To counter this, we need to change the increment to "number of children" (instead of "number of children - 1") but only for the root node. This is doable by noticing that `i` is at its initial value only at the start of a root `f` call and after processing the last leaf. So we can initialize `i` to 0 and when we increment `i`, we increment by "number of children" if `i` is 0 but by "number of children - 1" otherwise.
```
// 47 bytes
i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), (16) 21 bytes
```
Ôº∑Œ∏¬´‚ü¶Ôº©Ôº¨Œ∏‚üß‚âî‚Å∫‚à®ÔºÜ‚Å∞¬ßŒ∏‚Å∞œÖŒ¶Œ∏ŒªŒ∏
```
[Try it online!](https://tio.run/##HYxLC8IwEITP7a/Y4wYi1FdBPFVBEAR7DzmENrSBEMmjVhB/e9x2YWd2voHtRhW6l7I5z6OxGtAz@JZFG4xLKK4qJnxoN6SRCibZuSyaGM3gsLVTxGfAi0mzibpxPVYcmnR3vf6g51AxxmGivRmbdFiQXZCnJ7@chRA1hz0HsV3tICUJxd0aT3QdOdSSJm/e9g8 "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation:
```
Ôº∑Œ∏¬´
```
Repeat until the input list is empty.
```
‚ü¶Ôº©Ôº¨Œ∏‚üß
```
Output its length on its own line.
```
‚âî‚Å∫‚à®ÔºÜ‚Å∞¬ßŒ∏‚Å∞œÖŒ¶Œ∏ŒªŒ∏
```
Add the tail of the list to the first element.
* This would be three bytes shorter if the list was to be iteratively deleted from the end rather than the start.
* This would be four bytes shorter if Charcoal's vectorising `Add` worked properly, but unfortunately it only vectorises to depth 1. (Other operators, such as `BitwiseAnd`, do vectorise correctly, so I'm assuming this is an oversight. Edit: Ironically, `Times` also doesn't vectorise correctly, so I needed to replace it with `BitwiseAnd` to fix a bug.)
* Alternatively, this could be two bytes shorter if the input integers were all zero. (Not applicable when vectorising `Add` works properly.)
* This could be one byte shorter by outputting the last length instead of the first.
16 bytes using the newer version of Charcoal on ATO:
```
Ôº∑Œ∏¬´‚âî‚Å∫¬ßŒ∏‚Å∞Œ¶Œ∏ŒªŒ∏‚ü¶Ôº©Ôº¨Œ∏
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfDyzMyc1IVNAo1Faq5OB2LizPT8zQCckqLNRxLPPNSUis0CnUUDDR1FNwyc0pSi0C8HE0gt1DTmoszoCgzr0Qj2jmxuETDJzUvvSQDaI5mLFCqdklxUnIx1JLl0Uq6ZTlKsTe1o6OjzXQUjHUUog3BlElsLJAAco3AXEsgy1RHwSwWCCBaAQ "Charcoal ‚Äì Attempt This Online") Link is to verbose version of code. Outputs the last length instead of the first.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O·∏¢;$·∏ä‚Åº¬°¬µ∆¨·∫à·πñ
```
A monadic Link that accepts a ragged list of integers and yields the lengths as a list, including both the initial length and a trailing `0`.
**[Try it online!](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP///0dHm@koGOsoRBuCKZPYWCAB5BqBuZZAlqmOgllsbCwA "Jelly ‚Äì Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP86h9uPTnq4c8ajpjVZjxr36dppRv7/Hx0dbaijYBSroxBtDMQmOgqmsbGxXDrR0WY6CiARQzBlEgtUAZSMNgJzLYEsUx0FM4hSY7CUKVgXBBjGQgFQCISBhkQDDTAEKwHZBSRBJgJJrlgA "Jelly ‚Äì Try It Online").
### How?
```
O·∏¢;$·∏ä‚Åº¬°¬µ∆¨·∫à·πñ - Link: ragged list of positive integers, L
        ∆¨   - collect input, X (initially L), while distinct, applying:
       ¬µ    -   this monadic chain - f(X):
O           -     ordinal value (vectorises) -- only here to get us a copy of X
                                                so that we don't mutate it with ·∏¢
   $        -     last two links as a monad - f(Y=that):
 ·∏¢          -       head Y (alters Y, yields the first element or 0 when given [])
  ;         -       concatenate that with (the altered Y)
      ¬°     -     if...
     ‚Åº      -     ...condition: that equals X? (head of X was an integer)
    ·∏ä       -     ...then: dequeue
         ·∫à  - length of each
          ·πñ - pop the last length (removes the trailing 1, the length of 0)
```
---
Also 11 with no `·∏¢` and, therefore, no `O`: `1·ªã;·∏ä·∏ä‚Åº¬°¬µ∆¨·∫à·πñ`
[Answer]
# JavaScript (ES5), ~~¬†84¬†~~ 80 bytes
*Saved 4 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)*
```
function(a){for(r=[];m=a.shift(r.push(a.length));)a=m[0]?m.concat(a):a;return r}
```
[Try it online!](https://tio.run/##jVJPT4MwFL/vUzx3WNqkNmODRSXEkwc96MFj00NF2DCsJW1ZYpZ9dnyUbcGpiS/QPt77/WlpP9ROudxWjb/e3XSlsSQ32nkQlW5az8C0HmcJpgQxAQwBQkQMFpKBWOIbM0iklIDpggFWcIzGowTJzsxVgPQCOMUSReIz8RazhMHqqIaVJLTHySAbXxiNLZahnZwkfqxgiEgeA4bV/PKMWQE2LkT9dwD9YSMZuqA@E3KEWYyQksI@wIcfbgsHGZCubHXuK6OJovv@OGwmZLrNFHebqvTE8qZ1G6J4Xei131CaUpVtxVzebzkK5coj8U6ltvCt1WAPXW9BSThOmgbDqiRPry/P3Hlb6XVVfhI0p3CVZXBRF5zz4QYwmEsa2LMZ/Jc@UCmlYY@mLnht1mT6YK2xU9Zv@XTBcGWHyTfQYwnaHLug3syuYKDqGnzhvINGOVe8T2nafQE "JavaScript (V8) ‚Äì Try It Online")
Formatted and renamed:
```
function(array){
    result = [];
    while(
        result.push(array.length), 
        current = array.shift()
    ) {
        if(current !== +current) { // if current is not a number
            array = current.concat(array);
        }
    }
    return result;
}
```
[Answer]
# Rust, ~~19~~ ~~194~~ ~~185~~ 174 bytes
Even defining a type for a ragged list is bytes intensive in rust. Still shorter than C :)
```
enum K{N,Y(Vec<K>)}fn f(k:&K,n:usize)->Vec<usize>{if let K::Y(b)=k{[n+b.len()].into_iter().chain((1..).zip(b).map(|(i,z)|f(z,b.len()+n-i)).flatten()).collect()}else{vec![n]}}
```
Sequences will have a extra 0 at the end. [Verify all test cases](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c8474744bc710deb37a6d0546f7a477b)
-9 bytes by using `Vec` instead of array slices
-11 bytes by replacing `enumerate` with `zip` and `match` with `if let`
[Answer]
# BQN, 26 bytes
```
{(‚â†‚àæ¬∑ùïä=‚àò‚äë‚ó∂‚ü®‚ü©‚Äø‚äë‚àæ1‚ä∏‚Üì)‚çü(√ó‚â†)ùï©}
```
[Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlaniiaDiirjiiL4o8J2Vij3iiJjiipHil7bin6jin6nigL/iipHiiL4x4oq44oaTKeKNnyjDl+KJoCnwnZWpfQoKKOKAolNob3cgRuKImOKAokpzKcKo4p+oCiJbWzEsIDJdLCBbMywgWzQsIDVdXV0iCiJbWzYsIDMsIFsxLCAzLCA0XV0sIDQsIFsyLCAzLCA5LCBbNSwgNl1dXSIKIlszLCA0LCA1XSIKIltbW1tbW1tbMV1dXV1dXV1dIgoiW10iCiJbMSwgW10sIDFdIgoiW1tdLFtbW11dXSxbXV0iCuKfqQpA)
-1 byte thanks to @DLosc!
## Explanation
* `‚â†‚àæ¬∑...` append input length to...
* `(...)‚çü(√ó‚â†)ùï©` if input is nonempty...
* `...‚àæ1‚ä∏‚Üì` append tail to...
* `=‚àò‚äë‚ó∂‚ü®‚ü©‚Äø‚äë` head if head is rank 1 (i.e. list), otherwise empty list
* `ùïä` recurse
[Answer]
# [Factor](https://factorcode.org/), 57 bytes
```
[ [ dup length . unclip [ prepend ] when* ] until-empty ]
```
[Try it online!](https://tio.run/##lZFNb8IwDIbv/RXvrpOKBC0XkLhOu@yCOFUcqmDWiuCGNNWGqv72zsDSrwvCr2InVvzYSo6pcoVtd9vPr48VTmSZNEq6VMSKShhLzl2Nzdn12Rn9OpuWyAusg6AOIFaLjqLmHv3@pqm9IdzIhQUiWfNuNSPMwz8Q/WmI/cdEWCLu/A0UD8Ae6mHPrIOOJxrK9@81KZ5P5DHPu48w/ej1/Q2a10ZvgjZBgkNloIm/XYYZKlY6N5KVXzXEB@zxkxG/S6zY5Tqks3FX7KWStSRVcTZFSaBUZe0f "Factor ‚Äì Try It Online")
Input consists of ragged sequences of `f` ‚Äî Factor's canonical false value ‚Äî as this saves about 20 bytes over integers.
* `[ ... ] until-empty` Call `[ ... ]` on the input until it's empty.
* `dup length .` Print the current length of the input non-destructively.
* `unclip` Remove the first element from the sequence and place it on top of the data stack.
* `[ prepend ] when*` `when*` is like `when` except it drops its input value if it's false, but retains its input if it's true (which is any non-false value in Factor). So, prepend it to the input if it's a sequence, or drop it if it's `f`.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L140), 15 (non-competing‚Ä†) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
{‚îú_nn¬°¬ø\;+ho}‚ñ≤;
```
‚Ä† The program above doesn't compile due to a bug in MathGolf with (do-)while loops using blocks above 8 characters. `{...}` is supposed to be a block for when `...` contains more than 8 characters, but instead the `{` behaves as a for-each.
We can remove the `{}` and trailing `;` so the do-while works on all preceding characters, so we can verify the test cases. Unfortunately, all test cases will then output an additional trailing empty list `[]`.  
Both programs also fail with an error for input `[]`.
Outputs each length to STDOUT, without leading length and with trailing 0.
`‚îú_nn¬°¬ø\;+ho‚ñ≤`: [Try it online](https://tio.run/##LUq7DYNAFOtZJW4eHCdFGcVYiIZQEGgySpQqTVbIAkiMwiLHy4FlWf49uudwn8c@pe31aadp/a5Lc7sM8/b@pUQaSoEVGFBLKsgIT@YSJASwdHsFa8S8e@9P/x0wnSjoNFCw/ypkntZFOe4).
**Explanation:**
```
{           }‚ñ≤  # Do-while true with pop:
 ‚îú              #  Extract and push the left item of the list
                #  (this is where the `[]` test case errors)
  _             #  Duplicate it
   n            #  If it's a list: join it with newline delimiter to a string
                #  If it's an integer: push a newline "\n" character
    n¬°          #  Check that this string is NOT equal to "\n"
      ¬ø         #  If it's indeed not "\n" (thus it's a list)
       \        #   Swap the top two values
      ¬ø         #  Else (it's an integer):
        ;       #   Discard it from the stack
         +      #  If it's a list: merge the top two lists together
                #  If it's an integer: add it to each inner-most value
          h     #  Push the length (without popping the list)
           o    #  Output it with trailing newline (without popping)
             ‚ñ≤  #  Once the length is 0, the do-while stops
              ; # After the do-while: discard the empty list (since MathGolf
                # implicitly outputs the entire stack at the end of a program)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 266 bytes
```
#define S *w++=*r++
#define B b+=*r==91?1:-(*r==93)
f(r,b,w)char*r,*w;{w=++r;if(*++r==93)r++,r+=*r?*r==44:-1;else{if(*r!=44)for(b=1;b;B)S;r++;}for(;*r;)S;*w=0;}i;main(b,v,r)char**v,*r;{for(v++;*(*v+2);printf("%d ",i),f(*v))for(b=0,r=*v,i=1;*++r;B)(!b&&*r==44)&&i++;}
```
[Try it online!](https://tio.run/##PY7LbsIwEEX3fEWgauTHRMKUDYwsJH6BJfICh7i1VNJqWtmLiG93x6HtZh5X986Zvnvt@1KerkOI49CcGpW1toq0Xvxpx8ZXxdqdOZh9J@bxRS6CIPCQZf92IUWgMk7Zak0Yg1DcZxcfAqrxQ41tt/vO4PD@NUzVREtWZPgg4a1Bj0d5Qg7gvUqoCHlX2a7xHvF2iaPwkIAeQJWADVN1Jo4ooZLeSPykOH4HsXq@NiuIEpiS5C9iDWQ5FplV/2OcWPq2fTwm2zZWdCnlfDZgYC7Guf9xbs65Hw "C (gcc) ‚Äì Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes
```
0
[]
+`..(],?|(((\[)|(?<-4>])|,)+)])(.*)$
$&¬∂[$2$5
.(.((\[)|(?<-3>])|,)*].)*.?
$#1
```
[Try it online!](https://tio.run/##RY5LCsJADIb3OcWAo2TaGJy2UxDEHiQNVNCFGxfisufyAF5sTKeCgTz/LyHP2@v@uOQtTuO1hgM4yAcQhXpiRqVhRsRRwozDad@dNcwU6qABuQoe/O7zFt/4BIz859qVq5RDxQP4TcxZJJJrlJy05h25pKoAIj25ZRJL6tQIE6Up7dGqRK5f0bZIqWytFvVnsLwMyxGxA7EgSkaYRha@ "Retina 0.8.2 ‚Äì Try It Online") Outputs both leading and trailing counts and takes `0` as the consistent value (since `[]` is disallowed), but link is to test suite that replaces all non-negative integers with zero and deletes spaces for convenience. Explanation:
```
0
[]
```
Replace `0`s with empty lists.
```
+`
```
Repeat until the last line is an empty list.
```
..(],?|(((\[)|(?<-4>])|,)+)])(.*)$
```
On the last line, match a list containing either an empty list as its first or only element, or otherwise the contents of the list at the first element.
```
$&¬∂[$2$5
```
Keep the original list to count its elements later and create a new list obtained by prepending the contents (if any) to the rest of the list.
```
.(.((\[)|(?<-3>])|,)*].)*.?
$#1
```
Count the number of elements of each list.
[Answer]
## Brev, 85 bytes
```
(fn(descend(x)(cons(length x)(desc(if(pair?(car x))(append(car x)(cdr x))(cdr x))))))
```
Example:
```
((fn (descend (x)
              (cons
               (length x)
               (desc
                (if (pair? (car x))
                    (append (car x) (cdr x))
                    (cdr x))))))
 '((1 2) (3 (4 5))))
```
`fn` makes a function with an argument `x`. `descend` checks if it's null, if it is, return it. Otherwise, `cons` its `length` onto a recursive call of `descend`, where the `car` of `x` has been spliced if it's a `pair?` or dropped if it's an atom. For the test example, it returns `(2 3 2 1 2 1 2 1)`
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
#l=+|hQYt
```
[Try it online!](https://tio.run/##K6gsyfj/XznHVrsmIzCy5P//6GgDHQWDWB0FEA1hx8YCAA "Pyth ‚Äì Try It Online")
Accepts a ragged list filled with 0s.
Excludes the length of the initial list, and includes the 0 for the final list.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes
```
saj{g_Jto'B~[{j_+}qvvIEsaj}qL[w!
```
[Try it online!](https://tio.run/##VU3LCoJQEN33FZObFuHiPhTCcFG0KNy3kJACCUQoM20xTL9@O/lAPJcZLuc1t@ZV5nXV5I49P/aiyL88c1dfC75np/djtfumXGRrqdr2eAAtVZJ@lq4F9snWl3PpmBVpITbElgIRIT8m1mRIkxpHFswhKHgNWXhsb9kQBxSOIUMBhHH/o3aqQQWiuDBYh9YeSgZ0oqLZg63n8VHYYOYdggZkWSZed9oP "Burlesque ‚Äì Try It Online")
```
saj      # Get initial length
{
 g_      # Pop head from list
 J       # Dup
 to'B~[  # Is Block
 {j_+}   # Prepend elements
 qvv     # Drop
 IE      # If (isBlock) else
 saj     # Length
}
qL[w!    # While non-empty
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes
```
{‚ç¥‚ç¥‚çµ:‚àä(‚ç¥,‚àá¬®+‚ç¥-‚ç≥‚àò‚ç¥)‚çµ‚ãÑ0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvFjDaavWoo0sDyNR51NF@aIU2kKX7qHfzo44ZQJYmUP5Rd4tB7f@0R20TgKr6HnU1P@pdA5Q6tN74UdvER31Tg4OcgWSIh2ewJpD2Cvb3@5@mHh1tqKNgFKujEG0MxCY6CqaxsbHqXCAJMx0FkJghmDKJBaoBSkcbgbmWQJapjoIZTLExWNIUqhMCDGOhACwIIYGGRQMNMoQqjNUBqgOq0AES6gA "APL (Dyalog Classic) ‚Äì Try It Online")
I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then `‚àä` is not needed for -1 byte
Uses the same algorithm as my [other submission](https://codegolf.stackexchange.com/a/251282/6972), but pretty much ungolfed because tacit APL is that good
```
{‚ç¥‚ç¥‚çµ:‚àä(‚ç¥‚çµ),(‚àá¬®‚çµ)+(‚ç¥‚çµ)-(‚ç≥‚ç¥‚çµ)‚ãÑ0}  With trains expanded
                                
 ‚ç¥‚ç¥‚çµ:                           If argument is array
           (‚àá¬®‚çµ)                  recursive call with each element
                 +(‚ç¥‚çµ)-(‚ç≥‚ç¥‚çµ)      add (length of argument - index)
                                    note that APL arrays are 1-based by default
      (‚ç¥‚çµ),                       prepend length of argument
     ‚àä                            flatten
                           ‚ãÑ0   Else return 0
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth) (arbitrary values), 15 bytes
```
lM.u+.x[.*hN[)t
```
[Test suite](https://pythtemp.herokuapp.com/?code=lM.u%2B.x%5B.%2ahN%5B%29t&test_suite=1&test_suite_input=%5B%5B1%2C+2%5D%2C+%5B3%2C+%5B4%2C+5%5D%5D%5D%0A%5B%5B6%2C+3%2C+%5B1%2C+3%2C+4%5D%5D%2C+4%2C+%5B2%2C+3%2C+9%2C+%5B5%2C+6%5D%5D%5D%0A%5B3%2C+4%2C+5%5D%0A%5B%5B%5B%5B%5B%5B%5B%5B1%5D%5D%5D%5D%5D%5D%5D%5D%0A%5B%5D%0A%5B1%2C+%5B%5D%2C+1%5D%0A%5B%5B%5D%2C%5B%5B%5B%5D%5D%5D%2C%5B%5D%5D&debug=0)
Takes a ragged list of arbitrary values (even accepts floats). Includes length of original list and final 0.
##### Explanation:
```
lM.u+.x[.*hN[)t   | Full code
lM.u+.x[.*hN[)tNQ | with implicit variables
------------------+----------------------------------------------------------------------------------------------------------------
  .u            Q | Collect N, starting with the input, with each succussive N defined by the following until a result is repeated:
    +         tN  |  Prepend to the tail of N:
       [.*hN      |   N if N is a list
     .x     [)    |   or the empty list if N is not a list
lM                | Convert each element to its length
```
]