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..
lst =[] Update_MyList = [lst.append(MyList[z])for z in range(len(MyList)) if (10*MyList[z]-5 > 0)] Update_MyList.append(lst) print(Update_MyList)
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:
MyList = [1, -2, 3] Update_MyList = [10*x-5 if (10*x-5 > 0) else None for x in MyList] print(Update_MyList)
Output:
[5, None, 25]
After Edit
Code 2
If you don’t want None
for negative values, just remove else None
part. Here’s a code2:
MyList = [1, -2, 3] Update_MyList = [10*x-5 if (10*x-5 > 0) for x in MyList] print(Update_MyList)
Output:
[5, 25]
Code 3
If you are using python>=3.8, use the below code to avoid calculating 10*x-5 twice. Here’s a code3:
MyList = [1, -2, 3] Update_MyList = [y for x in MyList if (y := 10*x-5) > 0] print(Update_MyList)
Output:
[5, 25]