# Program to perform given operation with each element of a list and given value in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we also have another string op representing operator like "+", "-", "/", or "*", and another value val is also given, we have to perform the operation on every number in nums with val and return the result.

So, if the input is like [5,3,8], then the output will be [15, 9, 24]

To solve this, we will follow these steps −

• res:= a new list
• for each i in nums, do
• if op is same as '+', then
• insert i+val at the end of res
• otherwise when op is same as '-', then
• insert i-val at the end of res
• otherwise when op is same as '*', then
• insert i*val at the end of res
• otherwise when val is non-zero, then
• insert quotient of i/val at the end of res
• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums, op, val):
res=[]
for i in nums:
if op=='+':
res.append(i+val)
elif op=='-':
res.append(i-val)
elif op=='*':
res.append(i*val)
elif val:
res.append(i//val)
return res
ob = Solution()
nums = [5,3,8]
print(ob.solve(nums, '*', 3))

## Input

[5,3,8]

## Output

[15, 9, 24]
Updated on 06-Oct-2020 06:16:14