-1

I am calculating the age of the students from their date of birth and add it to the data:

def display(): 
    new = []
    print("\n                      STUDENT LIST")
    print("\n   ID   |    NAME    |    SURNAME    |  SEX  |   DOB   |     COB     |    AGE    \n")

    for line in students:
        line.append(age(str(line[4])))
        new.append(line)

    for newlines in new:
        print(newlines)

The problem is that the output of this keeps appending it to the very end every time the function is called. I want to be able to only append the lines that have a length of 6. The ones that already have a length of 6 should be ignored.

First Run:

First Run

Second Run:

Second Run

Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
Meric
  • 31
  • 3

4 Answers4

0

Lazy solution: Unconditionally delete anything beyond the expected length after appending:

for line in students:
    line.append(age(str(line[4])))
    del line[7:]  # Delete extra age if it already had one
    new.append(line)

Sure, you could just check the len(line) and not do the work if it's wrong, but branchless code is more fun.

ShadowRanger
  • 124,179
  • 11
  • 158
  • 228
0
for line in students:
        if len(line) == 6:  # If the line is only 6 items long
                line.append(age(str(line[4])))  # Then perform the append
        new.append(line)

Just check if the line is already more than 6 items, and if so, ignore it.

Omnikar
  • 152
  • 9
0

Try Using The PrettyTable Library:

There is a library in Python called "PrettyTable" Just go to your terminal and "pip install prettytable" to download the library Go to this link to learn more about the library: https://www.geeksforgeeks.org/creating-tables-with-prettytable-library-python/

I like this library because it's pretty easy to use and the code is pretty readable

0

After looking at it the next morning, I figured out the problem. I noticed a similar answer was made by Omnikar. Thank you so much everyone!

for line in test:
        if len(line) == 6:   # if the length is 6 append the lines
            line.append(age(str(line[4])))    # adding ages to list of all students
            new.append(line) 
        else:
            new.append(line)  # new lines in test that havent gotten the age conversion
Meric
  • 31
  • 3