Multiply each element of a list by a number in Python
In this tutorial, we will learn how to multiply each element of a list by a number in Python.
We can do this by two methods-
- By using List Comprehension
- By using for loop
Using List Comprehension
List comprehensions are used to define expressions or mathematical statements in one line instead of using a loop.
First, input a list from the user i.e. list1 and the number that the list needs to be multiplied with i.e. x. Now apply list comprehension.
list1 = [] new_list = [] n = int(input("\n Enter the range for input")) print("\n Enter the elements") for i in range (n): list1.append(int(input())) x = int(input("\n Enter the number to be multiplied")) new_list = [i * x for i in list1] print(new_list)
When we run the above code it will multiply each element of the list with the given number.
Input-
Enter the range for input 5 Enter the elements 1 2 3 4 5 Enter the number to be multiplied 2
Output-
[2, 4, 6, 8, 10]
Using for loop
First, input a list from the user i.e. list1 and the number that the list needs to be multiplied with i.e. x. Now apply for loop and multiply each element of the list with the given number.
list1 = [] new_list = [] n = int(input("\n Enter the range for input")) print("\n Enter the elements") for i in range (n): list1.append(int(input())) x = int(input("\n Enter the number to be multiplied")) for i in list1: new_list.append(x*i) print(new_list)
Input-
Enter the range for input 10 Enter the elements 1 2 0 9 3 4 8 7 4 5 Enter the number to be multiplied 3
Output-
[3, 6, 0, 27, 9, 12, 24, 21, 12, 15]
Leave a Reply