Is there an easier way to express this list slicing?

Neil Cerutti horpner at yahoo.com
Thu Nov 30 14:23:17 EST 2006


On 2006-11-30, John Henry <john106henry at hotmail.com> wrote:
> If I have a list of say, 10 elements and I need to slice it into
> irregular size list, I would have to create a bunch of temporary
> variables and then regroup them afterwords, like:
>
> # Just for illustration. Alist can be any existing 10 element list
> a_list=("",)*10
> (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list
> alist=(a,)
> blist=(b,)
> clist=(c1,c2,c3)
> dlist=(d2,d3,d4,d5)
>
> That obviously work but do I *really* have to do that?

Please post actual code we can run, rather than text that is
almost, but not quite, entirely unlike Python code.

> BTW: I know you can do:
> alist=a_list[0]
> blist=a_list[1]

Note that alist and blist are not necessarily lists, as you did
not use slice notation.

> clist=a_list[2:5]
> dlist=a_list[5:]
>
> but I don't see that it's any better.

I think it looks much better, personally.

If you are iterating through that sequence of slices a lot,
consider using a generator that yields the sequence.

  >>> def parts(items):
  ...   yield items[0:1]
  ...   yield items[1:2]
  ...   yield items[2:5]
  ...   yield items[5:]
 
  >>> for seq in parts(range(10)):
  ...   print seq
  [0]
  [1]
  [2, 3, 4]
  [5, 6, 7, 8, 9]
 
-- 
Neil Cerutti
I guess there are some operas I can tolerate and Italian isn't one of them.
--Music Lit Essay



More information about the Python-list mailing list