Reputation: 23
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?
Upvotes: 1
Views: 550
Reputation: 342
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.
Upvotes: 0
Reputation: 1
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)
Upvotes: 0
Reputation: 374
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.
Upvotes: 1