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]
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With