On 7 August 2013 17:59, Peter Otten <__pete...@web.de> wrote: > liuerfire Wang wrote: > >> Here is a list x = [b, a, c] (a, b, c are elements of x. Each of them are >> different type). Now I wanna generate a new list as [b, b, a, a, c, c]. >> >> I know we can do like that: >> >> tmp = [] >> for i in x: >> tmp.append(i) >> tmp.append(i) >> >> However, I wander is there a more beautiful way to do it, like [i for i in >> x]? > > Using itertools: > >>>> items > [b, a, c] >>>> from itertools import chain, tee, repeat > >>>> list(chain.from_iterable(zip(*tee(items)))) > [b, b, a, a, c, c] > > Also using itertools: > >>>> list(chain.from_iterable(repeat(item, 2) for item in items)) > [b, b, a, a, c, c]
list(chain.from_iterable([item, item] for item in items)) ? I'm actually posting to point out http://www.python.org/dev/peps/pep-0448/ would let you write: [*(item, item) for item in items] which I think is totz rad and beats out OP's [item for item in items for _ in range(2)] in readability, succinctness and obviousness. PS: For jokes, you can also painfully do: list((yield item) or item for item in items) > For lists only, should be fast: > >>>> result = 2*len(items)*[None] >>>> result[::2] = result[1::2] = items >>>> result > [b, b, a, a, c, c] > > But I would call none of these beautiful... Au contraire, that is marvelous (I'd still avoid it, though). -- http://mail.python.org/mailman/listinfo/python-list