# Operations with Lists

Inspired by this question.

Given a list containing numbers, print:

• The sum and product of the numbers in the list
• The average and median
• The differences between each term in the list (e.g. [1,2,3] -> [1,1]: 1+1=2, 2+1=3)
• The list, sorted ascending
• The minimum and maximum of the list
• The standard deviation of the list

For reference:

Standard Deviation

$$\sigma=\sqrt{\frac1N\sum^N_{i=1}(x_i-\mu)^2}$$

Where $$\\mu\$$ is the mean average, $$\x_i\$$ is the $$\i\$$th term in the list, and $$\N\$$ is the length of the list.

Shortest code wins. Good luck!

• Do we have to print them in that order? Oct 2, 2018 at 15:15

# Q, 41

{(+/;*/;avg;med;-':;asc;min;max;dev)@\:x}

• 'med'...facepalm Jun 8, 2012 at 11:14
• I was wondering what you were up to! Jun 8, 2012 at 12:04

# TI-BASIC, 41 bytes

1-Var Stats is one byte, and Σx, x̄, etc. are two bytes each.

Ans→L₁
1-Var Stats
SortA(L₁
Disp Σx,prod(Ans),x̄,Med,ΔList(Ans),L₁,minX,maxX,σx


If changing the output order is allowed, a close-paren can be saved, bringing the score to 40 bytes.

## J, 73 70 characters

((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)


Usage:

   ((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)1 2 3 4
+--+--+---+-+-------+-------+-+-+-------+
|10|24|2.5|3|1 1 1 1|1 2 3 4|1|4|1.11803|
+--+--+---+-+-------+-------+-+-+-------+

• It has to be 1 1 1 not 1 1 1 1 as difference itself next
– user58988
Jan 6, 2018 at 10:37

# Q (87 chars)

(sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\:


eg.

q) (sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\: 10 9 8 7 6 5 4 3 2 1
55
3628800
5.5
5.5
10 -1 -1 -1 -1 -1 -1 -1 -1 -1
s#1 2 3 4 5 6 7 8 9 10
1
10
2.872281


### Ruby 187

O=->l{g=l.size
r=l.sort
s=l.inject(:+)+0.0
m=s/g
p s,l.inject(:*),m,g%2>0?r[g/2]:(r[g/2]+r[g/2-1])/2.0,l.each_cons(2).map{|l|l-l},r,r,r[-1],(l.inject(0){|e,i|e+(i-m)**2}/g)**0.5}


Usage syntax: O[<array>] (for example, O[[1,2,3]])

Outputs all the required values to the console, in the order specified in the question.

IdeOne examples:

# Julia 0.6, 66 bytes

x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,std])|>show


Try it online!

# Julia 0.6, 88 bytes (uncorrected std dev, as in op)

x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,x->std(x,corrected=false)])|>show


Try it online!

• this isn't right, because Julia is using the sample standard deviation calculation (dividing by n-1) rather than the population std (dividing by n) as required in the problem. Multiplying by (n-1)/n wouldn't fix it either, because when dividing by n-1, NaN is produced. I ran into the same problems when trying to do this in R and haven't given it thought since. Jan 5, 2018 at 17:30
• That didn't even occur to me. I added an alternate solution with the correct std deviation.
– gggg
Jan 5, 2018 at 20:35
• Oct 6, 2021 at 15:31

### Scala 208202 188:

val w=l.size
val a=l.sum/w
val s=l.sortWith(_<_)
Seq(l.sum,l.product,a,s((w+1)/2),(0 to w-2).map(i=>l(i+1)-l(i)),s,l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/w))).map(println)


Test:

scala> val l = util.Random.shuffle((1 to 6).map(p=>math.pow(2, p).toInt))
l: scala.collection.immutable.IndexedSeq[Int] = Vector(64, 8, 4, 32, 16, 2)

scala> val a=l.sum/l.size
a: Int = 21

scala> val s=l.sortWith(_<_)
s: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 8, 16, 32, 64)

scala> Seq(l.sum,l.product,a,s((s.size+1)/2),(0 to l.size-2).map(i=>l(i+1)-l(i)),l.sortWith(_<_),l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/l.size))).map(println)
126
2097152
21
16
Vector(-56, -4, 28, -16, -14)
Vector(2, 4, 8, 16, 32, 64)
2
64
21.656407827707714

• For me "Vector(-56, -4, 28, -16, -14)" is wrong
– user58988
Jan 6, 2018 at 10:38
• @RosLuP: Why is it wrong? Jan 7, 2018 at 0:31
• Yes you are right if input is "Vector(64, 8, 4, 32, 16, 2)" ( i confuse the input)
– user58988
Jan 7, 2018 at 12:50

# Jelly, 27 bytes

_ÆmÆḊ÷L½$Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€  Try it online! ## How it works _ÆmÆḊ÷L½$ - Helper link. Takes a list l on the left
Æm       - Yield the mean of l
_         - Subtract the mean from each element of l
ÆḊ     - Calculate the norm
$- Run the previous two commands over l: L - Length of l ½ - Square root ÷ - Divide the norm by the square root of l's length Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€ - Main link. Takes a list l on the left W - Yield [l] ẋ9 - Repeat 9 times 9ƭ€ - Generate a 9 element list by running the previous 9 commands over l and collecting the results together: S - Sum P - Product Æm - Mean Æṁ - Median I - Forward increments Ṣ - Sort Ṃ - Minimum Ṁ - Maximum Ç - Helper link (standard deviation)  # Python 3.8, 174167148 147 bytes -7 bytes thanks to @wasif -19 bytes thanks to math.prod() -1 bytes thanks to @The Fifth Marshal lambda l:[sum(l),math.prod(l),mean(l),median(l),[m-n for n,m in zip(l,l[1:])],sorted(l),min(l),max(l),stdev(l)] import math from statistics import*  Try it online! • The code didn't work. Did you test it? Python doesn't have prod() and your forward differences calculation was wrong. I fixed it for you with 7 bytes saved Sep 23, 2021 at 16:35 • In PyCharm, math.prod works in Python 3.8. Maybe it is 3.8+ specific? Sep 23, 2021 at 16:42 • yes maybe. If that's the case you should add "3.8" to language name. But please also fix the forward differences calculation Sep 23, 2021 at 16:43 • math.prod indeed has been added in Python 3.8, so you might want to edit it back in again: docs.python.org/3.8/library/math.html#math.prod BTW: the post does not match the tio linked code Sep 27, 2021 at 13:10 • -1 byte Oct 4, 2021 at 18:32 # C++14, 340 383 bytes As generic unnamed lambda. First parameter L is the list as std::list of floating point type and second parameter is the desired output stream, like std::cout. #import<cmath> #define F(x);O<<x<<'\n'; #define Y l=k;++l!=L.end(); #define A auto [](A L,A&O){A S=L;A l=L.begin(),k=l;A n=L.size();A s=*l,p=s,d=s*s,h=n/2.;for(S.sort(),Y s+=*l,p*=*l,d+=*l**l);for(l=S.begin();--h>0;++l)F(s)F(p)F(s/n)F(*l)for(Y)O<<*l-*k++<<","F(' ')for(A x:S)O<<x<<","F(' ')F(S.front())F(S.back())F(sqrt((d-s*s/n)/(n-1)))}  Compiles with a warning, C++ does not allow " directly followed by literals like F. Program still running. • -1 & -2 bytes thanks to Zacharý Ungolfed: #include<iostream> #include<list> #import<cmath> #define F(x);O<<x<<'\n'; #define Y l=k;++l!=L.end(); #define A auto auto f= [](A L, A&O){ A S=L; //copy the list for later sorting A l=L.begin(), //main iterator k=l; //sidekick iterator A n=L.size(); A s=*l, //sum, init with head of list p=s, //product, same d=s*s, //standard deviation, formula see https://en.wikipedia.org/wiki/Algebraic_formula_for_the_variance h=n/2.; //for the median later for( S.sort(), //now min/med/max is at known positions in S Y //l=k;++l!=L.end(); //skip the headitem-loop s += *l, //l points the next element which is fine p *= *l, //since the head given at definiten d += *l * *l //needs the sum of the squares ); for( l=S.begin(); //std::list has no random access --h>0; //that's why single increment loop ++l //until median is crossed ) F(s) //;O<<s<<'\n'; //sum F(p) //product F(s/n) //average F(*l) //median (in S) for(Y) //l=k;++l!=L.end(); //set l back to L O<<*l-*k++<<"," //calc difference on the fly F(' ') for(A x:S) //output sorted list O<<x<<"," F(' ') F(S.front()) //minimum F(S.back()) //maximum F(sqrt((d-s*s/n)/(n-1))) //standard deviation } ; using namespace std; int main() { list<double> l = {10,3,1,2,4}; f(l, cout); }  • I think you can save a few bytes by changing F to ;F(x)O<<x<<'\n'; and the last line to: [](A L,A&O){A S=L;A l=L.begin(),k=l;A n=L.size();A s=*l,p=s,d=s*s,h=n/2.;for(S.sort(),Y s+=*l,p*=*l,d+=*l**l);for(l=S.begin();--h>0;++l)F(s)F(p)F(s/n)F(*l)for(Y)O<<*l-*k++<<","F(' ')for(A x:S)O<<x<<","F(' ')F(S.front())F(S.back())F(sqrt((d-s*s/n)/(n-1)));} Aug 11, 2017 at 22:38 • @Zacharý There was indeed an unnecessary ; quite at the end. That could be removed, but the compiler does not like " "F: warning: invalid suffix on literal; C++11 requires a space between literal and string macro it compiles though... Aug 11, 2017 at 22:48 • Does it work though?! Aug 11, 2017 at 22:54 • @Zacharý yes it does work. Aug 11, 2017 at 23:01 • 327 bytes Mar 17, 2019 at 23:13 # Perl 5, 204 + 1 = 205 bytes @L=sort{$a<=>$b}@F;$p=1;$s+=$_,$p*=$_,$a+=$_/@F for@L;for(0..$#F){$o=($F[$_]-$a)**2/@F;push@d,$F[$_]-$F[$_-1]if$_}$o=sqrt$o;$m=@F%2?$F[@F/2]:$F[@F/2]/2+$F[@F/2-1]/2;say"$s$p$/$a $m$/@d$/@L$/@L[0,-1]$/$o"


Try it online!

# Factor + math.unicode, 90 bytes

[| s | s Σ s Π s mean s median s differences s [ > ] sort s minmax s population-std .s ]


Try it online!

Should be pretty self-explanatory, I hope. Factor has a built-in for each of these, but only a few have short aliases. While cleaving is cool, it's much shorter to go with locals here. Locals are also shorter than storing the words in a list and using [ execute ] with each on them, which would eventually catch up if the list had been re-used even more.

# Pyt, 39 bytes

←ĐĐĐĐĐĐĐŞ⇹Ʃ3ȘΠ4Șµ5Ș₋⇹6Ș↕⇹7ȘṀ↔ĐĐµ-²Ʃ⇹Ł/√


This outputs, in order, the median, the product, the differences, the list reversed, the sum, the maximum and minimum, the mean, and the standard deviation.q

Try it online!

Explanation:

←ĐĐĐĐĐĐĐ                                              Push the array onto the stack 8 times
ş                                             Sort in ascending order
⇹                                            Stack management
Ʃ                                           Sum
3Ș                                         Stack management
Π                                        Product
4Ș                                      Stack management
µ                                     Mean (as a float)
5Ș                                   Stack management
₋                                  Differences
⇹6Ș                               Stack management
↕                              Minimum and maximum
⇹7Ș                           Stack management
Ṁ                          Median
↔                         Stack management
ĐĐµ-²Ʃ⇹Ł/√               Standard Deviation


# APL NARS, 119 chars, 182 bytes

{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂¯1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}



test

  h←{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂¯1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}
⎕fmt h 0
┌9──────────────────────┐
│        ┌0─┐ ┌1─┐      │
│0 0 0 0 │ 0│ │ 0│ 0 0 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
⎕fmt h 3
┌9──────────────────────┐
│        ┌0─┐ ┌1─┐      │
│3 3 3 3 │ 0│ │ 3│ 3 3 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
⎕fmt h 1 2 3
┌9───────────────────────────────────────┐
│        ┌2───┐ ┌3─────┐                 │
│6 6 2 2 │ 1 1│ │ 1 2 3│ 1 3 0.8164965809│
│~ ~ ~ ~ └~───┘ └~─────┘ ~ ~ ~~~~~~~~~~~~2
└∊───────────────────────────────────────┘
⎕fmt h 1 2 3 4
┌9────────────────────────────────────────────────┐
│              ┌3─────┐ ┌4───────┐                │
│10 24 2.5 2.5 │ 1 1 1│ │ 1 2 3 4│ 1 4 1.118033989│
│~~ ~~ ~~~ ~~~ └~─────┘ └~───────┘ ~ ~ ~~~~~~~~~~~2
└∊────────────────────────────────────────────────┘
⎕fmt h 1 2 7 3 4 5
┌9──────────────────────────────────────────────────────────────────┐
│                       ┌5──────────┐ ┌6───────────┐                │
│22 840 3.666666667 3.5 │ 1 5 ¯4 1 1│ │ 1 2 3 4 5 7│ 1 7 1.972026594│
│~~ ~~~ ~~~~~~~~~~~ ~~~ └~──────────┘ └~───────────┘ ~ ~ ~~~~~~~~~~~2
└∊──────────────────────────────────────────────────────────────────┘


# Ocaml - 288 bytes

Assuming the given list is a non-empty list of floats (to avoid conversions), and that the returned median is the weak definition of the median :

median l = n such that half the elements of l are smaller or equal to n and half the elements of l are greater or equal to n

open List
let f=fold_left
let z=length
let s l=f(+.)0. l
let a l=(s l)/.(float_of_int(z l))let rec i=function|a::[]->[]|a::b->(hd b -. a)::(i b)let r l=let t=sort compare l in(s,f( *.)1. l,a t,nth t((z t)/2+(z t)mod 2-1),t,i l,nth t 0,nth t((z t)-1),sqrt(a(map(fun n->(n-.(a l))**2.)l)))


open List

let sum l = fold_left (+.) 0. l
let prod l = fold_left ( *. ) 1. l
let avg l = (sum l) /. (float_of_int (length l))
let med l =
let center = (length l) / 2 + (length l) mod 2 -1 in
nth l center
let max l = nth l 0
let min l = nth l ((length l) - 1)
let dev l =
let mean = avg l in
sqrt (avg (map (fun n -> (n -. mean)**2.) l))

let rec dif =
function
| a::[] -> []
| a::b -> ((hd b) - a) :: (dif b)

let result l =
let sorted = sort compare l in
(
sum sorted,
prod sorted,
avg sorted,
med sorted,
sorted,
dif l,
max sorted,
min sorted,
dev sorted
)


# PHP, 213 bytes

function($a){echo$s=array_sum($a),_,array_product($a),_,$v=$s/$c=count($a);foreach($a as$i=>$x){$d+=($x-$v)**2;$i&&$f[]=$x-$a[$i-1];}sort($a);var_dump(($a[$c/2]+$a[$c/2+~$c%2])/2,$f,$a,$a,max($a),sqrt($d/\$c));}


# 05AB1E, 27 (or 25?) bytes

If the order is mandatory:

O,P,ÅA,Åm,¥,{R,ß,à,ÅA-nÅAt,


Try it online.

If the order doesn't matter:

O,P,Åm,¥,{R,ß,à,ÅA=-nÅAt,


Does the average just before the standard deviation, every other operation is in the same order.

Try it online.

Explanation:

O         # Sum the (implicit) input-list
,        # Pop and print it with trailing newline
P,        # Same for the product
ÅA,       # Same for the average
Åm,       # Same for the median
¥,        # Same for the deltas / forward differences
{R,       # Same for the descending sort (sort + reverse)
ß,        # Same for the minimum
à,        # Same for the maximum
# Same for the standard deviation:
ÅA        #  Get the average of the (implicit) input-list
-       #  Subtract it from each value in the (implicit) input-list
n      #  Square each
ÅA    #  Take the average of this list
t   #  Take the square-root of that
,  #  And print it as well
`