user75747475 - 1 year ago 61

Python Question

My goal is to multiply all positive numbers in a list by 3. I think I've almost got the solution but I'm not sure what is causing it not to work. It currently just returns back the original numbers and does not multiply any numbers by 3.

`def triple_positives(xs):`

List = []

product = 3

for i in range (len(List)):

if List[i] >= 0:

product *= i

List.append(xs[i])

return xs

Answer Source

In your code, there are multiple issues. Below is the updated version of it with fixes:

```
>>> def triple_positives(xs):
... List = []
... product = 3
... for i in range (len(xs)):
... if xs[i] >= 0:
... List.append(xs[i]*3)
... else:
... List.append(xs[i])
... return List
...
>>> my_list = [1, 2, -1, 5, -2]
>>> triple_positives(my_list)
[3, 6, -1, 15, -2]
```

Alternatively, you may achieve this using List Comprehension as:

```
>>> [item * 3 if item > 0 else item for item in my_list]
[3, 6, -1, 15, -2]
```