LambdaLabTM
Artificial Intelligence · Class 10 · Practical File · Program 1 of 15
Python & NumPyFrom the CBSE curriculum list⏱️ 6 min read

Program 1: Add the Elements of Two Lists

Write a program to add the elements of the two lists.

1Aim

Write a program to add the elements of the two lists.
Python 3NumPy (for the last part)

2Program

add_lists.py
# Program 1: Add the elements of two lists
# Each element of the first list is added to the element in the same
# position of the second list.

list1 = [10, 20, 30, 40, 50]
list2 = [5, 15, 25, 35, 45]

result = []
for i in range(len(list1)):
    result.append(list1[i] + list2[i])

print("List 1 :", list1)
print("List 2 :", list2)
print("Sum    :", result)
print()

# Careful: the + sign does NOT add two lists element by element.
# It joins them into one longer list.
print("list1 + list2 gives :", list1 + list2)
print()

# With NumPy arrays, + does add element by element.
import numpy as np
a = np.array(list1)
b = np.array(list2)
print("Using NumPy arrays  :", a + b)

3Output

The output of a real run, exactly as it appeared.

Output
List 1 : [10, 20, 30, 40, 50]
List 2 : [5, 15, 25, 35, 45]
Sum    : [15, 35, 55, 75, 95]

list1 + list2 gives : [10, 20, 30, 40, 50, 5, 15, 25, 35, 45]

Using NumPy arrays  : [15 35 55 75 95]

4How it works

for i in range(len(list1)):

Goes through the positions 0, 1, 2, 3, 4 — one for each element.

result.append(list1[i] + list2[i])

Adds the two elements in the same position and puts the answer at the end of the result list.

list1 + list2

With lists, + joins them into one longer list. It does not add the numbers. This is the most common mistake in this program.

np.array(list1) + np.array(list2)

NumPy arrays do add element by element, in one step, with no loop.

5Try this

  • Change the lists to hold 7 numbers each.
  • What happens if the two lists have different lengths? Try it, and read the error.
  • Subtract the lists instead of adding them.

6Viva questions

▸What does list1 + list2 do?

It joins the two lists into one list. It does not add the elements.

▸How can you add two lists element by element without a loop?

Convert them to NumPy arrays and use +.

▸What does range(len(list1)) give?

The positions 0 up to one less than the length of the list.

Tip
In your practical file, write the aim, the program and the output for each program — run it yourself and copy your own output. See The Practical File for how to set the file out.