Home > Software engineering >  Python List not getting appended in fuction
Python List not getting appended in fuction

Time:12-10

Since variables' values aren't changed inside a function, I first ran a tester for lists. It turns out they do get appended with the new values provided in the function. Here's what I tried


def test():
    testlist.append(6)


testlist=[3,4]

print(testlist)

test()

print(testlist)


output:-

[3, 4]

[3, 4, 6]

But when I tried this in my actual project it didn't work. Here's part of the code:-

student_name=[]
roll_number=[]

def student_info()
            
            sn=input("Student Name : ")
            student_name.append(sn)

            rn=input("Roll no. : ")
            roll_number.append(rn)


the student_info() runs as many times as there are students, which is also a variable.

Each time, the list appends a value for each student. All these values will later be extracted whenever needed using the index number. But when I try to call a list value it's always the first value of the list that comes. So the list is not being appended?


def print_card():
        for p in range(0,no_of_classes,1):
            for l in range(0,class_strength,1):
           
                print("Student Name:",student_name[l],x*50,"Roll No:",roll_number[l])
                
                

(please ignore the unnecessarily complex formatting part)


#This is the main part of the code.

for j in range (no_of_classes):
    
    class_=input("Class name")
    print("Class strength of ",class_)
    class_strength=int(input())
    
    for i in range (class_strength):
        student_info()
print_card()

Here's the minimum reproducible program


student_name=[]
roll_number=[]

def student_info():
            
            sn=input("Student Name : ")
            student_name.append(sn)

            rn=input("Roll no. : ")
            roll_number.append(rn)
            
def print_card():
        for p in range(0,no_of_classes,1):
            for l in range(0,class_strength,1):
                x=' '
                print('\n')
                print("Student Name:",student_name[l],x*50,"Roll No:",roll_number[l])

no_of_classes=2
class_strength=1

for j in range (0,no_of_classes):
    
    for i in range (0,class_strength):
        student_info()
        
        
print_card()

The card gets created for the first class but for the next class, the same output comes. Why is this happening?

Expected output vs Actual output

(say for 2 students)

                                      kode skool                                     
Student Name: 1                                                    Roll No: 1
Class: 1                                                           Section: 1
Address    1
           1


City:  1                                                        Pin Code: 1
Guardian's Phone Number 1


                                      kode skool                                        
Student Name: 2                                                    Roll No: 2
Class: 2                                                           Section: 2
Address    2
           2


City: 2                                                     Pin Code: 2
Guardian's Phone Number 2



-------------------------------------------------------------------



                                      kode skool  
Student Name: 1                                                    Roll No: 1
Class: 1                                                           Section: 1
Address    1
           1


City:  1                                                        Pin Code: 1
Guardian's Phone Number 1





                                      kode skool  
Student Name: 1                                                    Roll No: 1
Class: 1                                                           Section: 1
Address    1
           1


City:  1                                                        Pin Code: 1
Guardian's Phone Number 1




CodePudding user response:

All your problem is you keep all students on one flat list

students = [name1, name2, name3, ...] 

so later it makes problem to get correctly data for second class.

You use indexes [0], [1], etc. to get students from second class but it would need

[class_1_strength   0], [class_1_strength   1], etc.

And to get students from third class you would need

[class_1_strength   class_2_strength   0], [class_1_strength   class_2_strength   1], etc.

so it makes big problem.

It would be much simpler if you will keep every class as sublist

school = [
    [name1, name2, name3, ...], # class 1
    [name1, name2, name3, ...], # class 2
    # etc.
]

or as dictionary:

school = {
    'class_1_name': [name1, name2, name3, ...], # class 1
    'class_2_name': [name1, name2, name3, ...], # class 2
    # etc.
}

Frankly, it would be good to keep all values together:

school = [
    [ (name1, roll_number, ...),  (name2, roll_number, ...), ...], # class 1
    [ (name1, roll_number, ...),  (name2, roll_number, ...), ...], # class 2
    # etc.
]

Minimal working example.

I use random, string only to create some data for test - so I don't have to use input().

I use random.seed(0) to get always the same data - so I can compare them with previous execution.

import random
import string

random.seed(0)

def generate_random_name(lenght=5):
    return "".join(random.choices(string.ascii_uppercase, k=lenght))

def get_student_info():
    
    #student_name = input("Student Name : ")
    #roll_number  = input("Roll no. : ")

    student_name = generate_random_name()
    roll_number  = 1

    return student_name, roll_number
    
def print_card():
    for class_number, class_students in enumerate(school, 1):
        print('--- class:', class_number, '---\n')
        for item in class_students:
            student_name, roll_number, class_number = item

            print(f"Student Name: {student_name:}")
            print(f"Roll No: {roll_number}")
            print(f"Class: {class_number}")
            print()
        
# --- main ---

school = []

no_of_classes = 2
class_strength = 3

for class_number in range(1, no_of_classes 1):

    class_students = [] # list for all students in one clas

    for student_number in range(1, class_strength 1):

        student_name, roll_number = get_student_info()

        # all information about one student        
        item = [student_name, student_number, class_number]

        class_students.append(item)

    school.append(class_students)
        
print_card()

Result:

--- class: 1 ---

Student Name: VTKGN
Roll No: 1
Class: 1

Student Name: KUHMP
Roll No: 2
Class: 1

Student Name: XNHTQ
Roll No: 3
Class: 1

--- class: 2 ---

Student Name: GXZVX
Roll No: 1
Class: 2

Student Name: ISXRM
Roll No: 2
Class: 2

Student Name: CLPXZ
Roll No: 3
Class: 2
  • Related