[Python-il] elegant non contiguous slice

Omer Zak w1 at zak.co.il
Thu Dec 30 00:19:47 IST 2010


On Thu, 2010-12-30 at 00:11 +0200, Avishalom Shalit wrote:
> Is there a way to elegantly take the (e.g. ) 2nd 7th and 10th element in a list
> 
> i.e.
> more elegant than
> [arr[x] for x in [1,6,9] ]
> 
> along the lines of
> arr[1,6,9]
> 
> not a big issue, but i am curious

Unlike Perl, Python is based upon the principle of having exactly one
way to do each thing.
List comprehension (the [arr[x] for x in [1,6,9] ] method) is one way to
accomplish the goal, and it is reasonably parsimonious.  Therefore, it
is very unlikely to have another method of accomplishing the same.

However, if the indices themselves form an arithmetic sequence (such as
[1,5,9]), it is possible to use a slice notation: arr[1:10:4]

--- Omer


-- 
In a guided tour in Scotland:
 'And, what is worn under the kilt?'
 'Nothing.'
 'Huh?'
 'Nothing. It's all in perfectly good working order, thank you.'

My opinions, as expressed in this E-mail message, are mine alone.
They do not represent the official policy of any organization with which
I may be affiliated in any way.
WARNING TO SPAMMERS:  at http://www.zak.co.il/spamwarning.html



More information about the Python-il mailing list