1

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?

5 Answers 5

3

python 2.x

first, middle, last = a[0], a[1:-1], a[-1]
Sign up to request clarification or add additional context in comments.

3 Comments

Since this is about succinctness, you would have to include the additional assignment required here (a = [1,2,3,4,5]). Otherwise, if you want to do this on a literal in practice, you would have to spell out the literal three times.
Well, this doesn't make much sense with a literal. why not simply first, middle, last = 1, [2, 3, 4], 5..
@yi_H: I am not sure if I am right to do so, but I consider list-comprehensions to be list-literals.
2

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

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

2 Comments

It will be just slightly more efficient to do the pop first, of course. ;)
Just for the record in JavaScript it works as well (arr.shift() and arr.pop()).
1

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)

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.