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
x
5
1
lst =[]
2
Update_MyList = [lst.append(MyList[z])for z in range(len(MyList)) if (10*MyList[z]-5 > 0)]
3
Update_MyList.append(lst)
4
print(Update_MyList)
5
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
1
6
1
MyList = [1, -2, 3]
2
3
Update_MyList = [10*x-5 if (10*x-5 > 0) else None for x in MyList]
4
5
print(Update_MyList)
6
Output:
JavaScript
1
2
1
[5, None, 25]
2
After Edit
Code 2
If you don’t want None
for negative values, just remove else None
part. Here’s a code2:
JavaScript
1
6
1
MyList = [1, -2, 3]
2
3
Update_MyList = [10*x-5 if (10*x-5 > 0) for x in MyList]
4
5
print(Update_MyList)
6
Output:
JavaScript
1
2
1
[5, 25]
2
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
1
6
1
MyList = [1, -2, 3]
2
3
Update_MyList = [y for x in MyList if (y := 10*x-5) > 0]
4
5
print(Update_MyList)
6
Output:
JavaScript
1
2
1
[5, 25]
2