# Nesting list with a value repeated n amount of times

Given the input of n and value. The code is supposed to nest the single element list with value repeated n times. The final output should be a multilevel nested list with single repeated values in all sublists.

This is , so the shortest code in bytes wins!

## Test cases:

n = 1, value = 'a': ['a']
n = 2, value = 'a': ['a', ['a']]
n = 3, value = 'a': ['a', ['a', ['a']]]
n = 4, value = 'a': ['a', ['a', ['a', ['a']]]]
n = 5, value = 'a': ['a', ['a', ['a', ['a', ['a']]]]]
n = 6, value = 'a': ['a', ['a', ['a', ['a', ['a', ['a']]]]]]

• Is n always greater than zero? If so, can we take n 0-indexed?
– att
Commented Dec 20, 2021 at 4:44
• Do we need to include the commas in the output? And can the value be input as a string? Commented Dec 20, 2021 at 5:14
• @theorist Just a sequence is enough, in any way Commented Dec 20, 2021 at 5:17
• @att Yes. Always bigger than 0 Commented Dec 20, 2021 at 5:17
• @ZaMoC Sure.... Commented Dec 20, 2021 at 9:41

# Python 2, 33 30 bytes

-3 bytes thanks to @xnor

lambda n,v:eval('[v,'*n+']'*n)


Try it online!

• Wow! Good thought!! Commented Dec 20, 2021 at 7:10
• It looks like you can just do lambda n,v:eval('[v,'*n+']'*n)
– xnor
Commented Dec 20, 2021 at 7:28
• @xnor Haha! I honestly have no idea how I didn't see that... Commented Dec 20, 2021 at 7:30
• Even cooler now! Commented Dec 20, 2021 at 9:28

# 05AB1E, 3 bytes

F‚Ù


Try it online.

Explanation:

F     # Loop the first input amount of times:
‚    #  Pair the (implicit) second input-value with the current list
Ù   #  And uniquify it (which only does something in the first iteration,
#  transforming the pair of values to a single wrapped value)
# (after the loop, the result is output implicitly)

• 3 bytes! So far I think you're the winner. Commented Dec 27, 2021 at 10:29

# Vyxalr, 4 bytes

(⁰"U


Try it Online!

The joys of golfing language :)

## Explained

(⁰"U
(     # n times:
⁰    #   push the value
"U  #   pair and uniquify - a port of the 05ab1e answer

• Wow... 4 bytes!! Commented Dec 20, 2021 at 3:08
• That's so short... how- Commented Dec 20, 2021 at 3:08

# Python, 34 bytes

f=lambda x,n:n and[x,f(x,n-1)][:n]

Attempt This Online!

Thanks to loopy walt for this one.

## Python, 36 bytes

f=lambda x,n:[x][n>1:]or[x,f(x,n-1)]

Attempt This Online!

## Python, 36 35 bytes

f=lambda x,n:n*[1]and[[x]+f(x,n-1)]

Attempt This Online!

Outputs as a singleton list, but that feels like cheating here.

## Python, 39 bytes

f=lambda x,n:[x]+(~-n*[1]and[f(x,n-1)])

Attempt This Online!

## Python, 37 bytes

f=lambda x,n:x+(~-n*[1]and[f(x,n-1)])

Attempt This Online!

Inputs as a singleton list.

• Wow! Very clever! Commented Dec 20, 2021 at 3:07
• You can go zero-based and save two bytes in the topmost lambda (dropping >1). Commented Dec 20, 2021 at 6:11
• Well, they don't say no, do they? How about this f=lambda x,n:[x,n<2or f(x,n-1)][:n], then (35 bytes)? ato.pxeger.com/… Commented Dec 20, 2021 at 10:21
• 34 if you are ok with requiring n>0. ato.pxeger.com/… And I'm not dingledooper :-) Commented Dec 20, 2021 at 23:05
• @loopywalt sorry, your avatars are too similar ;) Commented Dec 20, 2021 at 23:12

# Proton, 25 bytes

n=>v=>((a=>[v,a])*n)([v])


Try it online!

n=>v=>((a=>[v,a])*n)([v])    This language is stupid
n=>                          Given n
v=>                        and v
(a=>[v,a])            pair v with the current accumulator
*n          n times
(            )([v])    and call that on [v]

• Thanks, very cool. "this language" is stupid lol Commented Dec 20, 2021 at 4:15
• @U12-F̉͋̅̾̇orward yep - I made this language, so I know better than anyone just how stupid it is :P Commented Dec 20, 2021 at 6:09
• Wow! Really! Very interesting. Cool. Commented Dec 20, 2021 at 7:12

# Wolfram Mathematica, 30 21 bytes

Print[""@@#~Nest~##]&


-9 bytes from @att!

Try it online!

Sample I/O:

Print[""@@#~Nest~##]&@@{a,3}


[a[a[a]]]

Print[""@@#~Nest~##]&@@{17,3}


[17[17[17]]]

Print[""@@#~Nest~##]&@@{Pi,6}


$$\[\pi [\pi [\pi [\pi [\pi [\pi ]]]]]]\$$

• Is a separator not needed? 21 bytes if so, or 27 bytes if it is.
– att
Commented Dec 20, 2021 at 5:06
• (with separator only works if value is a string)
– att
Commented Dec 20, 2021 at 5:10

# R, 46 bytes

function(n,v)Reduce(list,rep(v,n-1),list(v),T)


Try it online!

Non-recursive approach. Pretty-printing and test harness taken from Dominic van Essen who insisted I post this as my own.

• Nice; and based on the OP's reply to ZaMoC's comment/question, you can probably leave-out the ,T to save 2 bytes. Commented Dec 20, 2021 at 19:53

# BQN, 9 bytes

∾⟜⋈´⥊⟜⋈⟜⋈


Pins and bowties FTW

Anonymous tacit function that takes two arguments and returns a nested list. This is why the list formatting looks weird. Run it online!

### Explanation

The left argument is the count; the right argument is the value. The example uses a left argument of 2 and a right argument of 0.

∾⟜⋈´⥊⟜⋈⟜⋈
⟜⋈  Wrap the right argument in a list: ⟨ 0 ⟩, and then
⟜⋈     Wrap that list in a list: ⟨ ⟨ 0 ⟩ ⟩, and then
⥊        Reshape to a length equaling the left argument: ⟨ ⟨ 0 ⟩ ⟨ 0 ⟩ ⟩
´          Right-fold that list on this function:
⟜⋈             Wrap the right argument in a list: ⟨ ⟨ 0 ⟩ ⟩, and then
∾                Concatenate with the left argument: ⟨ 0 ⟩ ∾ ⟨ ⟨ 0 ⟩ ⟩ → ⟨ 0 ⟨ 0 ⟩ ⟩


# Husk, 13 bytes

+J',R¹e'[²R']


Try it online!

Not an ideal challenge for a language that doesn't support ragged lists...

+              # join together:
R¹         #  arg1 repeats of
e        #   2-element list of
'[      #    '[' and
²     #    arg2,
J',           #  joined by commas,
#  and
R']       #  arg1 repeats of ']'


# Jelly, 5 bytes

W{Ɱṭ/


Try it online!

Value on left, $$\n\$$ on right

W        The value wrapped in a singleton list
{Ɱ      for each 1..n.
ṭ/    Reduce by Funky Reverse Append™.

• Just curious, how do you type those characters? :) Commented Dec 20, 2021 at 4:15
• @U12-F̉͋̅̾̇orward abrudz.github.io/lb/jelly Commented Dec 20, 2021 at 4:36
• Wow!.... Interesting Commented Dec 20, 2021 at 5:18

# Ruby, 29 23 bytes

->n,a{eval'[a,'*n+?]*n}


Try it online!

Stole the eval trick from dingledooper

# R, 49 bytes

f=function(n,v)if(n-1,list(v,f(n-1,v)),list(v))


Try it online!

• 46 bytes Commented Dec 20, 2021 at 15:41
• @Giuseppe - that's a different answer. Post it. Commented Dec 20, 2021 at 16:23
• If you insist! Commented Dec 20, 2021 at 19:05

# Racket, 49 bytes

(define(f x n)(if(= n 1)(,x)(,x,(f x(- n 1)))))


Try it online!

• Welcome to Code Golf! Nice first answer. Commented Dec 20, 2021 at 23:15

# Wolfram Language (Mathematica), 24 bytes

t&@Do[t={#,t},Set@t;#2]&


Try it online!

Input [n, value].

# Wolfram Language (Mathematica), 24 bytes

0-indexed

Fold[List,{#},Table@##]&


Try it online!

• The order is reversed.
– att
Commented Dec 20, 2021 at 7:06
• @att I guess we will wait for OP to decide... Commented Dec 20, 2021 at 8:20
• The challenge specification clearly shows which order it should be in, which was OP's decision when they made the challenge in the first place. Commented Dec 20, 2021 at 9:18
• @hyper-neutrino OP says my answer is valid. Please check the main comments Commented Dec 20, 2021 at 9:43

# MathGolf, 5 bytes

a*Åαç


Outputs reversed (e.g. [[["a"],"a"],"a"] instead of ["a",["a",["a"]]]), which is allowed based on the comments under the challenge.

Try it online.

Explanation:

a      # Wrap the (implicit) input-string into a list
#  e.g. "abc" → ["abc"]
*     # Repeat it the (implicit) input-integer amount of times
#  e.g. 5 → ["abc","abc","abc","abc","abc"]
Å    # For-each over these strings,
# using the following 2 characters as inner code-block:
α   #  Wrap the top two values into a list
#  (which will wrap with the implicit loop-index 0 in the first iteration)
#   e.g. [0,"abc"] in the first iteration
#        [["abc"],"abc"] in the second iteration
#        [[["abc"],"abc"],"abc"] in the third, etc.
ç  #  Remove all 0s from the list with a falsey filter
#  (only relevant for the first iteration: [0,"abc"] → ["abc"])
# (after the loop, the entire stack is output implicitly as result)


# HBL, 11 bytes

1,(?(-.)(1('?(-.),)?)?


Try it!

### Explanation

A recursive function:

1,(?(-.)(1('?(-.),)?)?
1                       Cons
,                      the second argument with:
(?(-.)                 If the first argument decremented is truthy (> 1):
(1          )     Cons
('?     )        Recursive call with
(-.)           First argument decremented
,          Second argument unchanged
?      with nil (empty list)
Else (the first argument is 1):
?    Nil (empty list)


I.e., if the first argument is 1, we get (cons arg2 nil), which simply creates a singleton list containing the second argument; and if the first argument is greater than 1, we get (cons arg2 (cons [recursive-call] nil)), which wraps the result of the recursive call in a singleton list and then prepends the second argument to it.

# APL+WIN, 28 bytes

Prompts for n followed by value

(¯1↓∊n⍴⊂'[',⎕,','),(n←⎕)⍴']'


Try it online! Thanks to Dyalog Classic

• From the image it looks as if the outermost list (=box?) doesn't contain an 'a' alement... Commented Dec 20, 2021 at 20:03
• @DominicvanEssen Thanks for picking that up. I could not find an easy fix so went with a new approach Commented Dec 20, 2021 at 21:23
• Hmm... don't you now have an unwanted comma in the innermost list...? Commented Dec 20, 2021 at 21:52
• @DominicvanEssen Thanks again. Fixed. Old age seems to be getting the better of me ;( Commented Dec 20, 2021 at 22:14

# PHP, 56 55 bytes

function($n,$a){for($r=[$a];--$n;)$r=[$a,$r];return$r;}  Try it online! Like often, PHP makes the worst score, akin only to C, but dirtier and with lots of$

EDIT: -1 byte, these dollars allow us some trickery with the parser after all

function f($c,$n){return --$n?[$c,f($c,$n)]:[$c];}  Try it online! # PowerShell Core, 41 bytes $n,$a=$args
1..$n|%{$r=$a,@($r)|?{$_}}$r


Try it online!

Please note that this does not work for n = 1, for some reason PowerShell treats it as a string. Even when forcing to return an array.

Let me know if not OK and I'll withdraw this answer!

• Thanks for the answer, it's ok! doesn't matter much Commented Dec 20, 2021 at 4:17
• Or you could add an extra code for an if else for whether n is 1. Then just return the value in a singular list Commented Dec 20, 2021 at 4:18
• I tried but PowerShell doesn't want it: With an explicit .Net list for example Commented Dec 20, 2021 at 19:52

# Pari/GP, 29 bytes

f(a,n)=if(n--,[a,f(a,n)],[a])


Try it online!

# Charcoal, 15 bytes

ＦＮ≔⟦⁺⟦η⟧υ⟧υ⭆¹⊟υ


Try it online! Link is to verbose version of code. Explanation:

ＦＮ


Repeat n times...

≔⟦⁺⟦η⟧υ⟧υ


... prepend value to the initially predefined empty list, then wrap that in another list.

⭆¹⊟υ


Unwrap the very last wrapper list and pretty-print it.

# Pip-p, 14 13 bytes

-1 byte by porting Neil's Charcoal answer

Lal:[lPEb]l@0


Try it online!

### Explanation

Lal:[lPEb]l@0
l is empty list; a,b are command-line args
La             Loop a times:
b       b
PE        Prepended to
l          Current list
[    ]      Wrap that result in a singleton list
l:            Assign back to l
l    After the loop, l is our desired result wrapped in a singleton list
@0  So get the first element
and autoprint it, formatted as a list (-p flag)


# JavaScript (ES6), 24 bytes

-2 thanks to @tsh

n=>g=x=>--x?[n,g(x)]:[n]

• Why not --x instead.
– tsh
Commented Dec 20, 2021 at 8:25

# JavaScript (ES6), 27 bytes

f=(c,n)=>--n?[c,f(c,n)]:[c]


# Lua, 50 bytes

n,v=...t={v}for i=2,n do t={v,t}n=n-1 end return t


Try it online!

# Retina, 31 bytes

L$¶$*$([$', )$*] , (]+)$
$1  Try it online! Takes n and value on separate lines. Explanation: L$¶


Match the newline between n and value. This puts n in $ and value in $'.

$*$([$', )$*]


Wrap value in n lists.

, (]+)1


Remove the trailing comma in the innermost list.

# C (clang), 56 bytes

i;f(*x,n){for(i=~n;++i<n;)printf(i<0?",[%s"-i/n:"]",x);}


Try it online!

Takes a string literal as value and n , prints to std out the result.

for(i=~n;++i<n;)      - iterate from -n to n

printf(i<0?  - select format string:
",[%s"-i/n..x)  * new nest, -i/n to skip comma at first stage
:"]"            * close nest
$$$$


# Python, 38 bytes:

f=lambda n,v:[v,f(n-1,v)]if n>1else[v]


Try It Online!

• This doesn't work for n=1 Commented Dec 20, 2021 at 3:18
• @pxeger Edited mine! Commented Dec 20, 2021 at 3:23
• 36 bytes now... Commented Dec 20, 2021 at 9:30
• You can't remove the f= because this is a recursive function which requires itself to be assigned to f Commented Dec 20, 2021 at 19:21
• @pxeger dingledooper did Commented Dec 21, 2021 at 1:23