Shortest way to do this Python 3 list operation in PHP, JavaScript?


I am learning Python and I just read in a book that Python 3 lets you do this cool list operation:

first, *middle, last = [1, 2, 3, 4, 5]

first: 1 middle: [2, 3, 4] last: 5

This is great if I want to iterate through the middle of the list, and do separate things with the first and last items.

What's the easiest (read: most sugary) way to do this in Python 2.x, PHP, and JavaScript?


Python 2:

first, middle, last = a[0], a[1:-1], a[-1]


$first = array_shift($arr);
$last = array_pop($arr);
$middle = $arr;


var a = Array.apply(0,myAry), first = a.shift(), last = a.pop(), middle = a;

For the JavaScript sample, I created a copy of the array so as not to destroy the original.

By : kzh

On Python2, you can just use slice notation, also it's easier to read I think.

By : utdemir


list($first, $middle, $last) = array($array[0], array_splice($array, 1, -1), $array[1]);

It destroys the original array though, leaving only the first and last elements.

By : NikiC

This video can help you solving your question :)
By: admin