Home > Software design >  python multiply list elements inside list
python multiply list elements inside list

Time:10-06

I use lists to randomly pick an element over many iterations (to create artificial data sets). To change the probability of getting a certain element, I'm repeatedly adding those elements that should have a higher change of being picked, so instead of

fair_list = ["A", "B", "C"]

I would do

unfair_list = ["A", "B", "C", "C", "C"]

Is there a better way to do this inline? I tried

unfair_list = ["A", "B", 3 * "C"]

but this results in

["A", "B", "CCC"]

CodePudding user response:

You could do

unfair_list = ["A", "B"]
unfair_list  = ["C"] * 3

or

unfair_list = ["A", "B"]   ["C"] * 3

so you will get

unfair_list = ["A", "B", "C", "C", "C"]

CodePudding user response:

You can do it in one line actually.

unfiar_list = ["A", "B", *["C"]*3]
  • Related