Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!feeds.phibee-telecom.net!newsfeed.xs4all.nl!newsfeed3.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.004 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'only,': 0.07; 'wang': 0.07; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'tmp': 0.09; 'itertools': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-ipconnect.de': 0.16; 'subject:make': 0.16; 'elements': 0.16; 'wrote:': 0.18; '>>>': 0.22; 'import': 0.22; 'header:User-Agent:1': 0.23; 'skip:l 30': 0.24; 'header:X -Complaints-To:1': 0.27; 'subject:list': 0.30; 'lists': 0.32; 'but': 0.35; 'there': 0.35; 'should': 0.36; 'list': 0.37; 'to:addr :python-list': 0.38; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'new': 0.61; 'more': 0.64; 'different': 0.65; 'here': 0.66; 'beautiful': 0.68; 'repeat': 0.74 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Peter Otten <__peter__@web.de> Subject: Re: make elements of a list twice or more. Date: Wed, 07 Aug 2013 18:59:55 +0200 Organization: None References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Gmane-NNTP-Posting-Host: p5084afdd.dip0.t-ipconnect.de User-Agent: KNode/4.7.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 38 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1375894812 news.xs4all.nl 15917 [2001:888:2000:d::a6]:55461 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:52141 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] 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...