A query about list

Peter Otten __peter__ at web.de
Fri Oct 10 04:30:49 EDT 2003


Dave Benjamin wrote:

> In article <slrnbobkhq.io6.ramen at lackingtalent.com>, Dave Benjamin wrote:
>> In article <pan.2003.10.09.21.16.17.434674 at softhome.net>, Santanu
>> Chatterjee wrote:
>>> I was trying something like a.insert(1,a.pop(1)) but I need to
>>> modify a.pop(1) somehow so that the brackets vanish ...you know
>>> what I mean. Is that possible ?
>> 
>> Ahh, I see what you mean, now. You probably want slice assignment.
>> 
>> Try, for starters:
>> a[1:2] = a[1]
>> 
>> You'll probably still need to use type().
> 
> 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?
> 
>>>> 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]
> 
Here's a variant that might interest you. It entirely omits indices and
slices and can deal with recursively nested sequences.
You need not create a list at all, if you want to iterate over the elements
one at a time.

<code>
def flatten(seq):
    """ Flatten a sequence of sequences of sequences...
    """
    # avoid infinite recursion with strings
    if isinstance(seq, basestring):
        yield seq
    else:
        try:
            for i in seq:
                for k in flatten(i):
                    yield k
        except TypeError:
            yield seq

# seems to work with the borderline cases
assert list(flatten([1,[2,[3,4]],5,6,7,[8,9,10],11,12])) == range(1, 13)
assert "ABCDEFGHIJKL" == "".join(
    flatten(["A", ["B", ["C", "D"]], "E", "F", "G", ["H", "I", "J"], "K",
"L"]))
assert list(flatten([1, [], [2,3,4,5]])) == range(1, 6)
assert list(flatten([[[1,2],3], [4,[5,6]]])) == range(1, 7)
assert list(flatten([[]])) == []
assert list(flatten([])) == []

# but beware of infinite iterators anywhere in your tree...
#from itertools import count
#for i in flatten(count()): print i
</code>

Peter




More information about the Python-list mailing list