- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- if op is same as '+', then
- return res

Let us see the following implementation to get better understanding −

## Example

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]

- Related Questions & Answers
- AND a given scalar value with every element of a masked array in Python
- Raise each and every element of a masked array to a given scalar value in NumPy
- Raise a given scalar value to each and every element of a masked array in NumPy
- Program to reduce list by given operation and find smallest remaining number in Python
- Python program to sort and reverse a given list
- Write a program in Python to slice substrings from each element in a given series
- Create new linked list from two given linked list with greater element at each node in C++ Program
- Python – Append given number with every element of the list
- XOR a given scalar value with every element of a masked array in Python
- OR a given scalar value with every element of a masked array in Python
- Reduce the array to a single element with the given operation in C++
- AND every element of a masked array by a given scalar value in Python
- Python program to create a list of tuples from the given list having the number and its cube in each tuple
- Python Program to find the cube of each list element
- Python Program to assign each list element value equal to its magnitude order

Advertisements