Skip to content

PadLeft ​

Pad a list on the left to length n, or truncate it from the left.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguagePadLeft✓
PadLeft(list)a ragged array (a list of lists) padded with 0s to a full matrix.
PadLeft(list, n, x?)padded on the left with xx (default 0) to length nn; a shorter nn drops elements from the left instead.
Typed signatures
TypePackageApplies
(list<any>, integer?, any?) -> collectioncombinatoricsalways

Domain: Collections

Examples

Basic #

Padded with zeros on the left

live ↗
InPadLeft([1,2,3],5)\mathrm{PadLeft}(\bigl\lbrack1, 2, 3\bigr\rbrack, 5)Out[0,0,1,2,3]\bigl\lbrack0, 0, 1, 2, 3\bigr\rbrack

A padding element

live ↗
InPadLeft([1,2,3],5,x)\mathrm{PadLeft}(\bigl\lbrack1, 2, 3\bigr\rbrack, 5, x)Out[x,x,1,2,3]\bigl\lbrack x, x, 1, 2, 3\bigr\rbrack

Pads on the left with zeros to the requested length

live ↗
InPadLeft([a,b,c],10)\mathrm{PadLeft}(\bigl\lbrack a, b, c\bigr\rbrack, 10)Out[0,0,0,0,0,0,0,a,b,c]\bigl\lbrack0, 0, 0, 0, 0, 0, 0, a, b, c\bigr\rbrack

A custom padding element

live ↗
InPadLeft([a,b,c],10,x)\mathrm{PadLeft}(\bigl\lbrack a, b, c\bigr\rbrack, 10, x)Out[x,x,x,x,x,x,x,a,b,c]\bigl\lbrack x, x, x, x, x, x, x, a, b, c\bigr\rbrack

A padding list repeats cyclically, aligned to the right-hand end

live ↗
InPadLeft([a,b,c],10,[x,y,z])\mathrm{PadLeft}(\bigl\lbrack a, b, c\bigr\rbrack, 10, \bigl\lbrack x, y, z\bigr\rbrack)Out[z,x,y,z,x,y,z,a,b,c]\bigl\lbrack z, x, y, z, x, y, z, a, b, c\bigr\rbrack
Scope #

A shorter length drops elements from the left

live ↗
InPadLeft([1,2,3,4,5],3)\mathrm{PadLeft}(\bigl\lbrack1, 2, 3, 4, 5\bigr\rbrack, 3)Out[3,4,5]\bigl\lbrack3, 4, 5\bigr\rbrack

With no length, a ragged array is padded to a full matrix

live ↗
InPadLeft([[1],[2,3]])\mathrm{PadLeft}(\bigl\lbrack\bigl\lbrack1\bigr\rbrack, \bigl\lbrack2, 3\bigr\rbrack\bigr\rbrack)Out[[0,1],[2,3]]\bigl\lbrack\bigl\lbrack0, 1\bigr\rbrack, \bigl\lbrack2, 3\bigr\rbrack\bigr\rbrack

A negative length pads on the right instead

live ↗
InPadLeft([a,b,c],−10)\mathrm{PadLeft}(\bigl\lbrack a, b, c\bigr\rbrack, -10)Out[a,b,c,0,0,0,0,0,0,0]\bigl\lbrack a, b, c, 0, 0, 0, 0, 0, 0, 0\bigr\rbrack
Possible issues #

A nested padding list is used whole as the padding element

live ↗
InPadLeft([a,b,c],7,[[u,v]])\mathrm{PadLeft}(\bigl\lbrack a, b, c\bigr\rbrack, 7, \bigl\lbrack\bigl\lbrack u, v\bigr\rbrack\bigr\rbrack)Out[[u,v],[u,v],[u,v],[u,v],a,b,c]\bigl\lbrack\bigl\lbrack u, v\bigr\rbrack, \bigl\lbrack u, v\bigr\rbrack, \bigl\lbrack u, v\bigr\rbrack, \bigl\lbrack u, v\bigr\rbrack, a, b, c\bigr\rbrack

The padding cycle is aligned to the data, so it reads v,u,v,uv,u,v,u before the list

live ↗
InPadLeft([a,b,c],7,[u,v])\mathrm{PadLeft}(\bigl\lbrack a, b, c\bigr\rbrack, 7, \bigl\lbrack u, v\bigr\rbrack)Out[v,u,v,u,a,b,c]\bigl\lbrack v, u, v, u, a, b, c\bigr\rbrack
About
Examples10
Checked againstWolfram Language 10 agree
CrosswalkWolfram Language

See also: PadRight, Take