To divide a list by a scalar in Python, the easiest way is with list comprehension.

list_of_numbers = [1, 5, 2, 4]

print([num / 3 for num in list_of_numbers])

#Output:
[0.3333333333333333, 1.6666666666666667, 0.6666666666666666, 1.3333333333333333]

You can also use the Python map() function to apply a function and divide a list by a scalar.

list_of_numbers = [1, 5, 2, 4]

def divide_by_3(x):
    return lst / 3

print(list(map(divide_by_3,list_of_numbers)))

#Output:
[0.3333333333333333, 1.6666666666666667, 0.6666666666666666, 1.3333333333333333]

When working with collections of data, the ability to easily manipulate and change the values in those collections is valuable.

One example of this is if you have a list of numbers and want to divide each element in the list by a scalar value.

The easiest way to divide a list by a scalar in Python is with list comprehension.

List comprehension allows us to loop over a list, operate on each element, and create a new list.

Below is a simple example of how you can divide a list by 3 in Python with list comprehension.

list_of_numbers = [1, 5, 2, 4]

print([num / 3 for num in list_of_numbers])

#Output:
[0.3333333333333333, 1.6666666666666667, 0.6666666666666666, 1.3333333333333333]

Using map() to Divide Elements in a List by a Scalar Number in Python

The Python map() function allows you to apply a function to each element of a list.

We can use map() to divide all elements in a list by a number.

map() takes the name of a function, or a lambda function, and a list, and returns a map object which can be converted to a list.

Below is an example of how you can use map() to divide the elements of a list by a number in Python.

list_of_numbers = [1, 5, 2, 4]

def divide_by_3(x):
    return lst / 3

print(list(map(divide_by_3,list_of_numbers)))

#Output:
[0.3333333333333333, 1.6666666666666667, 0.6666666666666666, 1.3333333333333333]

How to Multiply List by Scalar with Python

If you want to go the other way, and multiply each number in a list by another number, then you can take the code from above and easily perform this operation with list comprehension.

Below is a simple example of how you can multiply a list by 3 in Python with list comprehension.

list_of_numbers = [1, 5, 2, 4]

print([num * 3 for num in list_of_numbers])

#Output:
[3, 15, 6, 12]

Hopefully this article has been useful for you to learn how to divide a list by a scalar with Python.

Categorized in:

Python,

Last Update: March 14, 2024

Tagged in: