[Python-ideas] list / array comprehensions extension

Masklinn masklinn at masklinn.net
Thu Dec 15 18:27:40 CET 2011


On 2011-12-15, at 17:26 , Alexander Heger wrote:
> 
> Or is there a way of doing this that in a similarly compact and
> obvious way I did not yet discover?

If the list is uniform, you can flatten a single level by using `itertools.chain`:

    >>> import itertools
    >>> x = [1,2,3]
    >>> y = itertools.chain.from_iterable([[0], x])
    >>> list(y)
    [0, 1, 2, 3]
    >>> # alternatively
    ... y = list(itertools.chain([0], x))
    >>> y
    [0, 1, 2, 3]
    >>> 

I know of no "better" way to do it at the moment, apart from using slice-assignment with a *stop* bound of 0:

    >>> y = [0, 0]
    >>> y[1:0] = x
    >>> y
    [0, 1, 2, 3, 0]




More information about the Python-ideas mailing list