Python Code Example: Arithmetic Functions on Lists

In this Python tutorial, we will explore how to perform basic arithmetic operations (such as addition, subtraction, multiplication, and division) on lists. Lists in Python can contain numeric values, and we can easily apply arithmetic operations to each element of the list. We will write a program that performs these operations and outputs the results. This exercise will help in understanding how to manipulate lists with arithmetic functions.

Code Example

# List of numbers
numbers = [10, 20, 30, 40, 50]

# Performing arithmetic operations
addition_result = sum(numbers)  # Sum of all elements in the list
subtraction_result = [num - 5 for num in numbers]  # Subtract 5 from each number
multiplication_result = [num * 2 for num in numbers]  # Multiply each number by 2
division_result = [num / 10 for num in numbers]  # Divide each number by 10

# Output the results
print("Sum of numbers:", addition_result)
print("Subtraction (each number - 5):", subtraction_result)
print("Multiplication (each number * 2):", multiplication_result)
print("Division (each number / 10):", division_result)

Output

Sum of numbers: 150
Subtraction (each number - 5): [5, 15, 25, 35, 45]
Multiplication (each number * 2): [20, 40, 60, 80, 100]
Division (each number / 10): [1.0, 2.0, 3.0, 4.0, 5.0]

Code Explanation

  1. List of Numbers: We start with a list of numbers: [10, 20, 30, 40, 50].
  2. Addition: We use the built-in sum() function to find the sum of all the numbers in the list.
  3. Subtraction: We use a list comprehension to subtract 5 from each number in the list. The result is a new list where each element is reduced by 5.
  4. Multiplication: Similarly, a list comprehension is used to multiply each element of the list by 2, resulting in a new list where each element is doubled.
  5. Division: A list comprehension is also used here to divide each element of the list by 10, producing a new list where each element is divided by 10.
  6. Output: We print the results of all the arithmetic operations, showing the sum of the list, the result of subtracting 5 from each number, multiplying each by 2, and dividing each by 10.

This code demonstrates how to perform basic arithmetic operations on each element of a list in Python using built-in functions and list comprehensions.