1

I'm just learning how to do list comprehensions. I was given this question:

Given a list of numbers, return the list with all even numbers doubled, and all odd numbers turned negative.

>>input_list=[72, 26, 79, 70, 20, 68, 43, -71, 71, -2]

Here is the code I wrote, but I'm not sure why I'm getting a "bad input" error:

output_list = [i * -1 if i < 0 if i%2==1 else i * 2 for i in input_list]

Can anyone tell me what is wrong with my code?

Humayun Ahmad Rajib
  • 1,502
  • 1
  • 10
  • 22
Simon Long
  • 23
  • 5
  • 2
    Why do you have two `if`s, and why are you checking `i < 0` at all? The task didn't say you need to do anything different for negative numbers. – user2357112 Apr 17 '20 at 03:26
  • 1
    I suppose if "odd numbers turned negative" means "set the sign to negative" instead of "negate", you might treat negative inputs differently, but that's not how you do it (and also it'd be easier to use `-abs(i)`). – user2357112 Apr 17 '20 at 03:29
  • I would suggest to take a look at this: https://stackoverflow.com/a/15248309/10798048 – Dhruv Agarwal Apr 17 '20 at 03:37
  • Does this answer your question? [if/else in a list comprehension?](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension) – Joshua Hall Apr 17 '20 at 05:00
  • The `map`,`lambda` function in python are made just for handling above scenario. Take a look https://www.python.org/dev/peps/pep-0308/ – Shahir Ansari Apr 17 '20 at 07:10

3 Answers3

1

I am assuming you don't want to change the number at all if it is an odd negative number:

output_l = [x*2 if x % 2 == 0 else x*-1 if x > 0 else x for x in input_list]

The key here is to use two conditionals within the list comprehension. The first will check whether to double the number (if even number) and the second will check whether to negate the number (if it is odd and positive) or remain as it is if already negative.

Remember that you cannot add two if statements sequentially. You have to define an else in between.

Leafar
  • 364
  • 2
  • 10
  • Thank you, it worked. That's exactly what I was trying to do. It's super helpful to know I have to define and else in between haha – Simon Long Apr 18 '20 at 22:07
0

Try this Instead

input_list = [72,26,79,70,20,68,43,-71,71,-2]
output_list=[ x*2 if x%2==0 else -1*abs(x) for x in  input_list]
print(output_list)

or :[false,true][condition] is the syntax:

input_list = [72,26,79,70,20,68,43,-71,71,-2]
output_list=[[-1*abs(x),x*2] [x%2==0] for x in  input_list]
print(input_list)
print(output_list)
Ake
  • 1
  • 2
0

Your answer was given in this question: if/else in a list comprehension?

input_list = [72, 26, 79, 70, 20, 68, 43, -71, 71, -2]
output_list = [i*2 if i % 2 == 0 else abs(i) * -1 for i in input_list]
print(output_list)

If you are using if and else this is how to format it.

Joshua Hall
  • 332
  • 4
  • 15