'Duplicate numbers in list with list comprehension
I'm trying to duplicate all numbers in a list of alpha values as cleanly as possible but can't figure out how.
alphas = [.001, .01, .1, 1, 10, 100]
data_alphas = [a for num in alphas for i in range(2)]
This should return
[.001, .001, .01, .01, .1, .1, 1, 1, 10, 10, 100, 100]
Solution 1:[1]
I think the fastest and easiest way is to just duplicate the list and sort it.
alphas = [.001, .01, .1, 1, 10, 100]
data_alphas = sorted(alphas * 2)
Solution 2:[2]
This feels kinda "hacky" and is probably not the most pythonic way to solve this but it should work.
alphas = [.001, .01, .1, 1, 10, 100]
data_alphas = [alphas[int(i/2)] for i in range(len(alphas)*2)]
It outputs
[0.001, 0.001, 0.01, 0.01, 0.1, 0.1, 1, 1, 10, 10, 100, 100]
Solution 3:[3]
You can try something like:
list(sum(zip(v, v), ()))
sorry for one-liner, there might be better options though
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | imerla |
| Solution 2 | Marko Borkovi? |
| Solution 3 | zubrabubra |
