We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Adding a Column to a Table

Sometimes, when working with nested lists (tables), we may want to add an extra column to each row based on some logic or condition. This is a powerful feature of Python that helps with data transformation.


Example Scenario

Suppose we have a table of students with their test scores, and we want to add a new column indicating whether they passed or failed (assuming a pass mark is 70).

students = [
    ["Alice", 85],
    ["Bob", 65],
    ["Charlie", 92]
]

for student in students:
    score = student[1]
    if score >= 70:
        student.append("Pass")
    else:
        student.append("Fail")

print(students)

Output

[['Alice', 85, 'Pass'], ['Bob', 65, 'Fail'], ['Charlie', 92, 'Pass']]

Now, each sublist (row) contains 3 values — name, score, and result.

Displaying the Updated Table Nicely

We can format the output to make it more readable using a loop:

for student in students:
    print(f"{student[0]} scored {student[1]} - {student[2]}")

Output

Alice scored 85 - Pass
Bob scored 65 - Fail
Charlie scored 92 - Pass

Real-World Example: Adding Total Score Column

Let’s say we have a nested list with students and scores in 3 subjects. We can add a column that contains the total score.

records = [
    ["Alice", 70, 80, 90],
    ["Bob", 60, 55, 72],
    ["Charlie", 88, 90, 95]
]

for record in records:
    total = record[1] + record[2] + record[3]
    record.append(total)

print(records)

Output

[['Alice', 70, 80, 90, 240], ['Bob', 60, 55, 72, 187], ['Charlie', 88, 90, 95, 273]]

Exercise: Try It Yourself!

  1. Create a list of students with scores in two subjects.
  2. Add a third column that is the average of the two scores.
  3. Add a fourth column that says "Excellent" if the average is 90 or above, otherwise "Needs Improvement".

Example starting point

grades = [
    ["Jake", 88, 94],
    ["Lily", 76, 80],
    ["Tom", 95, 98]
]

# Your code here