# Separating elements from a list according to preceding element

Gerard Flanagan grflanagan at yahoo.co.uk
Sun Mar 5 22:42:49 CET 2006

```Alex Martelli wrote:
> Gerard Flanagan <grflanagan at yahoo.co.uk> wrote:
>     ...
> > a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]
> >
> > import itertools
> >
> > b = list(itertools.islice(a,0,8,2))
> > c = list(itertools.islice(a,1,8,2))
>
> Much as I love itertools, this specific task would be best expressed ad
>
> b = a[::2]
> c = a[1::2]
>

Yes, I thought that when I saw bruno's solution - I can't say that I've
never seen that syntax before, but I never really understood that this
is what it did.

> Do note that you really don't need the 'list(...)' here, for the
> following use:
>
> > result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
> > result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']
>
> ...would be just as good if b and c were islice objects rather than
> lists, except for the issue of _repeating_ (izipping twice).

I couldn't get it to work without the 'list(...)' , it seems you must
have to 'rewind' the islice, eg. this works:

b = itertools.islice(a,0,8,2)
c = itertools.islice(a,1,8,2)

result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']

b = itertools.islice(a,0,8,2)
c = itertools.islice(a,1,8,2)

result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']

but not without that 're-assignment' of b and c.

> I'd rather
> do some variant of a single-loop such as:
>
> results = {'+':[], '-':[]}
> for operator, tag in itertools.izip(a[::2], a[1::2]):
>     results[operator].append(tag)
>
> and use results['+'] and results['-'] thereafter.
>
> These approaches do not consider the inconvenient fact that the leading
> '+' does in fact not appear in list a -- it needs to be assumed, the OP
> stated; only a '-' would instead appear explicitly. Little for it but
> specialcasing depending on whether a[0]=='-', I think -- e.g. in the
> above 3-line snippet of mine, insert right after the first line:
>
> if a[0]!='-': results['+'].append(a.pop(0))
>
>
> Alex

Cheers

Gerard

```