Reputation: 7657
What's the most pythonic way to do the following? It can either modify the old list or create a new list.
oldList = [1, 2, 3, 4]
newList = [1, 1, 2, 2, 3, 3, 4, 4]
Upvotes: 2
Views: 148
Reputation: 51
a=[1,2,3,4]
print a*2
This will print [1,2,3,4,1,2,3,4]
This can be used if you want duplicate of elements
if you want the duplicate to be next to the original the below code can be used
a=[1,2,3,4]
b=[]
for i in range(0,len(a)):
b.append(a[i])
b.append(a[i])
print b
this will print b=[1,1,2,2,3,3,4,4]
Upvotes: 0
Reputation: 304117
>>> oldList = [1, 2, 3, 4]
>>> (4*(oldList+[0]+oldList))[::5]
[1, 1, 2, 2, 3, 3, 4, 4]
Strangely enough
$ python -m timeit -s "oldList = [1, 2, 3, 4]" "[x for x in oldList for _ in range(2)]"
1000000 loops, best of 3: 1.65 usec per loop
$ python -m timeit -s "oldList = [1, 2, 3, 4]" "(4*(oldList+[0]+oldList))[::5]"
1000000 loops, best of 3: 0.995 usec per loop
Upvotes: 1
Reputation: 304117
Since nobody has done an answer that modifies oldList in place. Here's a fun way
>>> oldList = [1, 2, 3, 4]
>>> oldList += oldList
>>> oldList[::2] = oldList[1::2] = oldList[-4:]
>>> oldList
[1, 1, 2, 2, 3, 3, 4, 4]
Upvotes: 2
Reputation: 12755
Two more approaches using functional concepts:
>>> list_ = [1,2,3,4]
>>> from itertools import chain
>>> list(chain(*[[x,x] for x in list_]))
[1, 1, 2, 2, 3, 3, 4, 4]
>>> reduce(lambda x,y: x+y, [[x,x] for x in list_])
[1, 1, 2, 2, 3, 3, 4, 4]
And one using numpy:
list(np.array([[x,x] for x in list_]).flatten())
And one last as list comprehension:
[x for y in zip(list_, list_) for x in y]
Upvotes: 1
Reputation: 25954
If you're really into functional programming:
from itertools import chain,izip
newList = list(chain(*izip(oldList,oldList)))
@falsetru's answer is more readable, so that likely meets the "most pythonic" litmus test.
Upvotes: 4
Reputation: 368894
Using list comprehension:
>>> oldList = [1, 2, 3, 4]
>>> newList = [x for x in oldList for _ in range(2)]
>>> newList
[1, 1, 2, 2, 3, 3, 4, 4]
Above list comprehension is similar to following nested for loop.
newList = []
for x in oldList:
for _ in range(2):
newList.append(x)
Upvotes: 9