Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52141 > unrolled thread

Re: make elements of a list twice or more.

Started byPeter Otten <__peter__@web.de>
First post2013-08-07 18:59 +0200
Last post2013-08-07 18:59 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: make elements of a list twice or more. Peter Otten <__peter__@web.de> - 2013-08-07 18:59 +0200

#52141 — Re: make elements of a list twice or more.

FromPeter Otten <__peter__@web.de>
Date2013-08-07 18:59 +0200
SubjectRe: make elements of a list twice or more.
Message-ID<mailman.321.1375894812.1251.python-list@python.org>
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...

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web