# How can I thread lists of different sizes?

What I need is the equivalent of Maple's zip(+, A, B, 0). Sure I can get it with:

Thread[PadRight[A, max = Max[Length[A], Length[B]]] + PadRight[B, max]]


But is there a less verbose way to do this?

P.S. Eventually the shortest solution seems to be:

 Plus @@ PadRight[{A, B}]

• Possible duplicate: mathematica.stackexchange.com/q/22437/121 – Mr.Wizard Jan 29 '14 at 16:51
• In your code Thread is useless (because Plus is Listable) and PadRight[A, max = Max[Length[A], Length[B]]] + PadRight[B, max] can be rewritten as Plus @@ PadRight[{A,B}] – andre314 Jan 29 '14 at 19:30
• 'Plus' was used as an example – user6109 Jan 29 '14 at 21:18

a = {1, 2, 3};
b = {q, r, s, t, u};
Plus @@@ Flatten[{a, b}, {2}]

{1 + q, 2 + r, 3 + s, t, u}


For convenience:

SetAttributes[myThread, HoldFirst]
myThread[h_[args__]] := h @@@ Flatten[{args}, {2}]


Now:

myThread[a + b]

{1 + q, 2 + r, 3 + s, t, u}


This utility may also be useful.

The reason I showed use of Flatten rather than PadRight is that it is more general. With PadRight your function will see zeros:

Times @@ PadRight[{a, b}]

{q, 2 r, 3 s, 0, 0}


Compare to:

myThread[a*b]

{q, 2 r, 3 s, t, u}


Of course for Times you could pad with ones, but the point is that the padding element would have to be changed to match the function, and for some functions no padding element would be correct.

• Transposing ragged arrays with Flatten[array,{2}] is one of my favorite tricks. – kale Jan 30 '14 at 0:38

Another possibility, which I cannot judge as equivalent to Maple's zip, is to use Distribute:

a = {1, 2, 3};
b = {q, r, s, t, u};

Distribute[f[a, b], List]


{f(1,q),f(1,r),f(1,s),f(1,t),f(1,u),f(2,q),f(2,r),f(2,s),f(2,t),f(2,u),f(3,q),f(3,r),f(3,s),f(3,t),f(3,u)}

If f is List, the result is:

Distribute[{a, b}, List]


{{1, q}, {1, r}, {1, s}, {1, t}, {1, u}, {2, q}, {2, r}, {2, s}, {2, t}, {2, u}, {3, q}, {3, r}, {3, s}, {3, t}, {3, u}}

• I don't believe this answers the question. The result should be {1 + q, 2 + r, 3 + s, t, u} – Simon Woods Jan 29 '14 at 21:21
• @SimonWoods Yes you are right: now I understood better the question. Thanks – user8074 Jan 29 '14 at 21:54
• Delete then perhaps? – Mr.Wizard Jan 30 '14 at 0:32