
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Program to reduce list by given operation and find smallest remaining number in Python
- AND a given scalar value with every element of a masked array in Python
- Python – Append given number with every element of the list
- Python program to sort and reverse a given list
- Reduce the array to a single element with the given operation in C++
- Create new linked list from two given linked list with greater element at each node in C++ Program
- Write a program in Python to slice substrings from each element in a given series
- 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 perform excel spreadsheet operation in Python?
- 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
- Python Program – Strings with all given List characters
- Program to find smallest string with a given numeric value in Python
- Python program to create a list of tuples from the given list having the number and its cube in each tuple

Advertisements