Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: duplicating each element in a list

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]
like image 282
jayelm Avatar asked Feb 21 '26 09:02

jayelm


2 Answers

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)
like image 121
falsetru Avatar answered Feb 22 '26 22:02

falsetru


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.

like image 45
roippi Avatar answered Feb 22 '26 21:02

roippi