Skip to content
Advertisement

list comprehension, how to append the new elements to the list?

am working on my Python assessment and I need a hand :( so, the task is to use this equation: 10*x-5 and print positive numbers only; the task focuses on using list comprehension, finally, I’ve to print the updated list. I did all of that but i couldn’t figure out how to insert/append the updated elements to the new list, so here is what’ve done..

JavaScript

all what I get is:[None, None, None, None, None]

Advertisement

Answer

Code1

Assuming your MyList is [1, -2, 3] and you want to print None when output is negative. Here’s a code1:

JavaScript

Output:

JavaScript

After Edit


Code 2

If you don’t want None for negative values, just remove else None part. Here’s a code2:

JavaScript

Output:

JavaScript

Code 3

If you are using python>=3.8, use the below code to avoid calculating 10*x-5 twice. Here’s a code3:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement