Slice a list of lists?
usenot at geekmail.INVALID
Wed Sep 8 22:44:52 CEST 2010
On Wed, 8 Sep 2010 15:23:35 -0500 Jonno <jonnojohnson at gmail.com> wrote:
> On Wed, Sep 8, 2010 at 3:18 PM, Jonno <jonnojohnson at gmail.com> wrote:
> > Now if I want to select the first item in every 2nd item of list a
> > (ie: [1,7]) can I use ::2 anywhere or do I need to create a list of
> > indices to use in a more complex for loop?
> Seems like the simplest way would be:
> [row for row in a][::2]
What you're doing here is selecting every second item of the list of
first items of the items in a, not the first items of every second item
in a (head spinning yet?).
If I'm not completely mindbent right now, these are logically
equivalent, but not computationally.
[row for row in a][::2] # (your Python code)
[row for row in a[::2]] # (as per your description)
The first one is more work for your computer, because it'll pick out
the first elements of *all* of the items in a, whereas the second only
picks out the first elements of every second item in a (which is only
half the amount of "picks" compared to the former).
I just thought I'd mention it. Because it might make a difference in
one of your programs some day. And because I'm a pedant ;).
More information about the Python-list