DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 22: Nested Lists, Nested Loops, List Operations & Exam Marks Analysis

1. Understanding Nested Lists

A list can contain different types of data, such as:

  • String
  • Integer
  • Float
  • Boolean
  • Another List

When a list contains another list as an element, it is called a Nested List.

Example:

l1 = [10, 20, 30, 40]
l2 = [40, 30, 20, 10]

l3 = [l1, l2]

print(len(l3))
print(l3)
Enter fullscreen mode Exit fullscreen mode
Output:

2
[[10, 20, 30, 40], [40, 30, 20, 10]]
Enter fullscreen mode Exit fullscreen mode

Here:

  • l1 contains four elements.
  • l2 contains four elements.
  • l3 contains two lists. ** Important:** len(l3) returns 2 because the outer list contains two elements, and each element is itself a list.

2. Accessing Elements from Multiple Lists

Suppose we have two lists:

l1 = [10, 20, 30, 40]
l2 = [40, 30, 20, 10]

Our task is to add elements at the same index.

We can perform this manually:

print(l1[0] + l2[0])
print(l1[1] + l2[1])
print(l1[2] + l2[2])
print(l1[3] + l2[3])
Enter fullscreen mode Exit fullscreen mode
Output:

50
50
50
50
Enter fullscreen mode Exit fullscreen mode

But what if the lists contain 100 elements?

Writing every statement manually is not practical. We can use a loop.

3. Adding Elements from Two Lists Using a While Loop

We can use a while loop to access the elements using their indexes and add them.

l1 = [10, 20, 30, 40]
l2 = [40, 30, 20, 10]

l4 = []

i = 0

while i < len(l1):
    l4.append(l1[i] + l2[i])
    i += 1

print(l4)

Enter fullscreen mode Exit fullscreen mode
Output:

[50, 50, 50, 50]
Enter fullscreen mode Exit fullscreen mode

Let's understand the logic:

  1. Create an empty list called l4.
  2. Initialize the index i = 0.
  3. Check whether i is less than the length of l1.
  4. Access elements from both lists using the same index.
  5. Add the values and store the result using append().
  6. Increment the index by 1.
  7. Repeat until the condition becomes false.

This approach works when both lists have the same length.

4. Iterating Through a Nested List

Let's understand how to access elements from a nested list.

l1 = [10, 20, 30, 40]
l2 = [40, 30, 20, 10]

l3 = [l1, l2]

for each_list in l3:
    print(each_list)
Enter fullscreen mode Exit fullscreen mode
Output:

[10, 20, 30, 40]
[40, 30, 20, 10]
Enter fullscreen mode Exit fullscreen mode

Here, the outer loop accesses each individual list.

Using Nested Loops

What if we want to access every element inside the nested list?

We can use one loop inside another loop. This is called a Nested Loop.


for inner_list in l3:
    for each_element in inner_list:
        print(each_element, end=' ')
Enter fullscreen mode Exit fullscreen mode
Output:

10 20 30 40 40 30 20 10
Enter fullscreen mode Exit fullscreen mode

Let's understand:

  • Outer loop: Selects each inner list.
  • Inner loop: Accesses every element inside that selected list.

Remember: A nested loop is a loop inside another loop.

5. Adding Two Lists with Different Lengths

What happens if two lists have different numbers of elements?

Example:

l1 = [10, 20, 30, 40.4]
l2 = [30.2, 40.3, 50, 60, 70, 80, 90]

Here:

  • l1 contains 4 elements.
  • l2 contains 7 elements.

Our requirement is:

  • Add elements at the same index while both lists have elements.
  • If one list has extra elements, add those remaining elements to the result. ** Understanding the Ternary Operator**

First, we need to find the smaller list length.

Python provides a conditional expression, commonly called the Ternary Operator.

Syntax:

value_if_true if condition else value_if_false

Example:

small = len(l1) if len(l1) < len(l2) else len(l2)
Enter fullscreen mode Exit fullscreen mode

Here:

  • If l1 has fewer elements, its length is selected.
  • Otherwise, the length of l2 is selected.
l1 = [10, 20, 30, 40.4]
l2 = [30.2, 40.3, 50, 60, 70, 80, 90]

small = len(l1) if len(l1) < len(l2) else len(l2)

l3 = []

i = 0

while i < small:
    l3.append(l1[i] + l2[i])
    i += 1

while i < len(l2):
    l3.append(l2[i])
    i += 1

print(l3)
Enter fullscreen mode Exit fullscreen mode
Output:

[40.2, 60.3, 80, 100.4, 70, 80, 90]
Enter fullscreen mode Exit fullscreen mode

Let's understand the logic:

First while loop:

Adds the elements from both lists at the same index until the shorter list ends.

Second while loop:

Adds the remaining elements from the longer list.

This example assumes l2 is the longer list. If either list can be longer, we need to handle both possibilities.

6. Working with Exam Marks Using Nested Lists

Now let's take a real-world example.

Imagine a student has written three exams. Each exam contains five subject marks.

q = [90, 80, 67, 58, 49]
h = [87, 89, 99, 47, 36]
a = [56, 78, 46, 67, 69]

exams_list = [q, h, a]
Enter fullscreen mode Exit fullscreen mode

Here:

  • q represents the first exam.
  • h represents the second exam.
  • a represents the third exam.
  • exams_list contains all three exam lists.

Finding the Total Marks in Each Exam

We can use nested loops to calculate the total marks.

for each_exam in exams_list:
    total = 0

    for each_mark in each_exam:
        total += each_mark

    print(total)
Enter fullscreen mode Exit fullscreen mode
Output:

344
358
316
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The outer loop selects one exam.
  • The inner loop accesses each subject mark.
  • total += each_mark adds every mark to the total.
  • After completing one exam, the total is printed.

7. Finding the Highest Total Among Three Exams

Now our requirement is to find which exam has the highest total marks.

We can use a while loop along with a for loop.

q = [90, 80, 67, 58, 49]
h = [87, 89, 99, 47, 36]
a = [56, 78, 46, 67, 69]

exams_list = [q, h, a]

highest_total = 0
i = 0

while i < len(exams_list):

    total = 0

    for each_mark in exams_list[i]:
        total += each_mark

    print(total)

    if total > highest_total:
        highest_total = total

    i += 1

print("Highest Total:", highest_total)
Enter fullscreen mode Exit fullscreen mode
Output:

344
358
316
Highest Total: 358
Enter fullscreen mode Exit fullscreen mode

The second exam has the highest total of 358.

Understanding highest_total

Initially:

highest_total = 0

After calculating each exam's total, we compare it with highest_total.

If the current total is greater, we update highest_total.

This way, we always maintain the highest total found so far.

Task: Find the average mark of each subject across all three exams using a single while loop.

q = [90, 80, 67, 58, 49]
h = [87, 89, 99, 47, 36]
a = [56, 78, 46, 67, 69]

exams_list = [q, h, a]

i = 0

while i < len(q):
    total = q[i] + h[i] + a[i]
    average = total // len(exams_list)

    print("Subject Index:", i)
    print("Average:", average)

    i += 1
Enter fullscreen mode Exit fullscreen mode
output:
Subject Index: 0
Average: 77

Subject Index: 1
Average: 82

Subject Index: 2
Average: 70

Subject Index: 3
Average: 57

Subject Index: 4
Average: 51
Enter fullscreen mode Exit fullscreen mode

How it works

  1. i represents the subject index.
  2. Add the marks from all three exams at that index.
  3. Divide the total by 3 to calculate the average.
  4. Increase i and repeat until all subjects are completed.

For example, subject index 0:

(90 + 87 + 56) // 3 = 77

8. Finding the Highest Mark in a Single Exam

Let's find the highest mark in the first exam.

q = [90, 80, 67, 58, 49]

highest = 0

for each_mark in q:
    if each_mark > highest:
        highest = each_mark

print(highest)
Enter fullscreen mode Exit fullscreen mode

Output:

90
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Initialize highest = 0.
  • Read each mark from the list.
  • Compare the current mark with highest.
  • If the current mark is greater, update highest.
  • Finally, print the highest mark.

9. Finding the Highest Mark Across All Three Exams

Now let's find the highest individual mark among all three exams.

q = [90, 80, 67, 58, 49]
h = [87, 89, 99, 47, 36]
a = [56, 78, 46, 67, 69]

high_score = 0

highest = 0
for each_mark in q:
    if each_mark > highest:
        highest = each_mark

if highest > high_score:
    high_score = highest

highest = 0
for each_mark in h:
    if each_mark > highest:
        highest = each_mark

if highest > high_score:
    high_score = highest

highest = 0
for each_mark in a:
    if each_mark > highest:
        highest = each_mark

if highest > high_score:
    high_score = highest

print('High Score in all 3 Exams is', high_score)
Enter fullscreen mode Exit fullscreen mode
Output:

High Score in all 3 Exams is 99
Enter fullscreen mode Exit fullscreen mode

The highest individual mark across all three exams is 99.

Important concept:

  • highest stores the highest mark in the current exam.
  • high_score stores the highest mark across all exams.

We reset highest = 0 before checking each new exam, but we don't reset high_score.

Practice Tasks

1. Find the highest mark across all exams using while loop

q = [90, 80, 67, 58, 49]
h = [87, 89, 99, 47, 36]
a = [56, 78, 46, 67, 69]

high_score = 0
i = 0

while i < len(q):
    if q[i] > high_score:
        high_score = q[i]

    if h[i] > high_score:
        high_score = h[i]

    if a[i] > high_score:
        high_score = a[i]

    i += 1

print("Highest Mark:", high_score)
Enter fullscreen mode Exit fullscreen mode
output:
Highest Mark: 99
Enter fullscreen mode Exit fullscreen mode

2. Find which exam got the highest mark

q = [90, 80, 67, 58, 49]
h = [87, 89, 99, 47, 36]
a = [56, 78, 46, 67, 69]

high_score = 0
exam_number = 0
i = 0

while i < len(q):
    if q[i] > high_score:
        high_score = q[i]
        exam_number = 1

    if h[i] > high_score:
        high_score = h[i]
        exam_number = 2

    if a[i] > high_score:
        high_score = a[i]
        exam_number = 3

    i += 1

print("Highest Mark:", high_score)
print("Exam Number:", exam_number)
Enter fullscreen mode Exit fullscreen mode
output:
Highest Mark: 99
Exam Number: 2
Enter fullscreen mode Exit fullscreen mode

3. Find which Exam, which subject [index], he /she gets the highest mark

q = [90, 80, 67, 58, 49]
h = [87, 89, 99, 47, 36]
a = [56, 78, 46, 67, 69]

high_score = 0
exam_number = 0
subject_index = 0
i = 0

while i < len(q):
    if q[i] > high_score:
        high_score = q[i]
        exam_number = 1
        subject_index = i

    if h[i] > high_score:
        high_score = h[i]
        exam_number = 2
        subject_index = i

    if a[i] > high_score:
        high_score = a[i]
        exam_number = 3
        subject_index = i

    i += 1

print("Highest Mark:", high_score)
print("Exam Number:", exam_number)
print("Subject Index:", subject_index)
Enter fullscreen mode Exit fullscreen mode
output:
Highest Mark: 99
Exam Number: 2
Subject Index: 2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)