Matt Montag
Matt Montag

Reputation: 7481

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?

Upvotes: 1

Views: 213

Answers (5)

kzh
kzh

Reputation: 20598

Python 2:

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

PHP:

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

JavaScript:

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.

Upvotes: 0

NikiC
NikiC

Reputation: 101936

In PHP:

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.

Upvotes: 1

utdemir
utdemir

Reputation: 27216

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

>>> t = (1, 2, 3, 4, 5)
>>> a, b, c = t[0], t[1:-1], t[-1]
>>> a, b, c
(1, (2, 3, 4), 5)

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96266

python 2.x

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

Upvotes: 3

user142162
user142162

Reputation:

A solution in PHP could be the following, using array_shift and array_pop:

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

Upvotes: 2

Related Questions