A query about list

Terry Reedy tjreedy at udel.edu
Thu Oct 9 18:24:44 EDT 2003


"Dave Benjamin" <ramen at lackingtalent.com> wrote in message
news:slrnbobkr7.io6.ramen at lackingtalent.com...
> This *seems* to work, but I have a sneaking feeling there's a bug in
here as
> a result of the slice assignment. I haven't been able to find a
boundary
> case that breaks this, but it seems like the slice assignment would
mess up
> the indexes in the loop. Can anyone find a way to either break or
improve
> this?

I believe enumerate is a generator which makes one pair at a time, as
needed.  If so, then you are iterating over inserted items after the
first, which may or may not be what is wanted.  I believe an empty
sublist would be deleted, shifting remainder to left and skipping next
item.  Try [1, [], [2,3,5]] and also [[[1,2],3], [4,[5,6]]]

> >>> a = [1, [2, 3, 4], 5, 6, 7, [8, 9, 10], 11, 12]
> >>> def flatten_sublists(lst):
> ...     for i, item in enumerate(lst):
> ...         if type(item) is type([]):
> ...             lst[i:i+1] = lst[i]
> ...
> >>> flatten_sublists(a)
> >>> a
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

If my hypothesis is correct, I might rewrite with while i loop to
either iterate over either all (for multilevel flatten) or none (for
two-level flatten) of inserted items.

Terry J. Reedy






More information about the Python-list mailing list