Reputation: 40778
I would like to duplicate the items of a list into a new list, for example
a=[1,2]
b=[[i,i] for i in a]
gives [[1, 1], [2, 2]]
, whereas I would like to have [1, 1, 2, 2]
.
I also found that I could use:
b=[i for i in a for j in a]
but it seemed like overkill to use two for
loops. Is it possible to do this using a single for
loop?
Upvotes: 0
Views: 136
Reputation: 180540
You could use xrange
and using a generator expression or a list comprehension
b = (x for x in a for _ in xrange(2))
b = [x for x in a for _ in xrange(2)]
Upvotes: 1
Reputation: 89097
You want itertools.chain.from_iterable()
, which takes an iterable of iterables and returns a single iterable with all the elements of the sub-iterables (flattening by one level):
b = itertools.chain.from_iterable((i, i) for i in a)
Combined with a generator expression, you get the result you want. Obviously, if you need a list, just call list()
on the iterator, but in most cases that isn't needed (and is less efficient).
If, as Ashwini suggests, you want each item len(a)
times, it's simple to do that as well:
duplicates = len(a)
b = itertools.chain.from_iterable([i] * duplicates for i in a)
Note that any of these solutions do not copy i
, they give you multiple references to the same element. Most of the time, that should be fine.
Upvotes: 2
Reputation: 12310
Your two-loop code does not actually do what you want, because the inner loop is evaluated for every step of the outer loop. Here is an easy solution:
b = [j for i in a for j in (i, i)]
Upvotes: 1
Reputation: 85693
if you do not mind the order:
>>> a = [1,2]
>>> a * 2
[1, 2, 1, 2]
Upvotes: 0