Home > Net >  Duplicate numbers in list with list comprehension
Duplicate numbers in list with list comprehension

Time:03-23

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]

CodePudding user response:

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)

CodePudding user response:

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]

CodePudding user response:

You can try something like:

list(sum(zip(v, v), ()))

sorry for one-liner, there might be better options though

  • Related