0

hi I wrote a code to take number of students and number of lessons I have a array I want to put grades of lessons and average of them in array but it does not work and code just prints last input instead of all students this is my code:

def find_averag(numberOfLessons, grades, linenumber):
    sum = 0
    for x in range(numberOfLessons):
        sum += grades[linenumber][x + 1]
    return sum / numberOfLessons


val = input("Enter number of students: ")
numberOfStudents = int(val)
val = input("Enter number of lessons : ")
numberOfLessons = int(val)

arr = [[0] * (numberOfLessons + 2)] * numberOfStudents
print(arr)
for x in range(numberOfStudents):
  val = input("Emter student name: ")
  print(val)
  arr[x][0] = val
  print(arr[x][0])
  for y in range(numberOfLessons):
      val = input("Enter grade")
      degree = int(val)
      arr[x][y+1] = degree
arr[x][numberOfLessons + 1] = find_averag(numberOfLessons, arr, x)
for t in range(numberOfStudents):
        print(arr[t])

1 Answer 1

1

This is a key Python concept. Let's say numberOfLessons is 3 a numberOfStudents is 5. Then, this statement:

arr = [[0] * (numberOfLessons + 2)] * numberOfStudents

Does not actually create a 3x5 array. What it creates is a list with 5 pointers to the SAME 3-element list. If you change array[0][0], that's also going to be seen in array[1][0] and array[4][0].

The easy way to handle this is to build up your array from nothing, adding a row at a time:

arr = []
print(arr)
for x in range(numberOfStudents):
  val = input("Emter student name: ")
  print(val)
  row = [val]
  print(row)
  for y in range(numberOfLessons):
      val = input("Enter grade")
      degree = int(val)
      row.append( degree )
  arr.append( row )
Sign up to request clarification or add additional context in comments.

2 Comments

Or if you want to pre-create a list of lists in one expression, use a list comprehension: arr = [[0] * (numberOfLessons + 2)] for x in range(numberOfStudents)]
That's a good point, but in my experience it's usually more readable and more "Pythonic" to build up the list of lists like I have done here. The desire to pre-create 2D arrays usually comes from another language. On the other hand, with numpy, the pre-create option makes good sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.