-3

I have a big list of numbers like;

original_list = [20,10,15,56,80,200,47,12, 4,70,...]

I want to raise the numbers by 20 percent where they are less than 50, and keep the rest as they are in the list in the original order.

Is there any single comprehension method to make the second list without using function? perhaps;

revised_list =[x*1.2 for x in original_list if x < 50 else y for y in original_list]
mozway
  • 194,879
  • 13
  • 39
  • 75
Leo Sam
  • 83
  • 1
  • 12
  • Obscure solution: `revised_list = list(map(lambda x:x*[1,1.2][v<50], original_list))` – Matthias Dec 06 '22 at 20:51
  • @Matthias: Yeah, I resisted the urge to suggest a similar approach using a listcomp (`lambda`s are the devil), `[x*(1, 1.2)[x < 50] for x in original_list]` (using a `tuple` to avoid it being reconstructed each time), or the similar `[x + x * .2 * (x < 50) for x in original_list]` that uses the boolean as its numeric value to zero out or keep the result of `x * .2`. The conditional expression is the sane way to go though. :-) – ShadowRanger Dec 06 '22 at 21:01
  • Even if it's a duplicate, don't remove the content, this makes it worse. Eventually delete the answer, or just leave it as it is. This might help other users being routed to the duplicate. – mozway Apr 27 '23 at 08:28

2 Answers2

0

You need to use the if/else conditional operator on the value production alone, not the whole attempt at a listcomp:

revised_list = [x*1.2 if x < 50 else x for x in original_list]

which only applies the multiplier if x < 50, and otherwise preserves the original x value.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
-1

To get a varying function you can use the python ternary expression:

revised_list = [x*1.2 if x < 50 else x for x in original_list]
quamrana
  • 37,849
  • 12
  • 53
  • 71