Inputing integers in nested for loops to 2D arrays are replaced by inputed values in incrementation

33 Views Asked by At
league_size = int(input("How many teams are in the league?"))
match_no = int(input("How many maches are played?"))
team_points = [[0]*match_no] * league_size

for i in range(len(team_points)):
    for j in range(len(team_points[i])):
        point = int(input("Input point of " + str(j+1) + " match"))
        team_points[i][j] = point
print(team_points)

When I enter values in the first loop they are saved correctly, but then as i is incremented the values that I entered before incrementing are replaced by the values I entered in the incrementation.

team_points = [[0,0,0], [0,0,0]]

for i in range(len(team_points)):
    for j in range(len(team_points[i])):
        point = int(input("Input point of " + str(j+1) + " match"))
        team_points[i][j] = point
print(team_points)

While if I do the inputs manually the values are changed correctly.

1

There are 1 best solutions below

0
On

This line is the problem:

[[0]*match_no] * league_size

What you're doing here is creating a single list on the form [0, 0, 0, ...] with a length of match_no, and then you're creating a list containing league_size duplicates of the same list. I.e, if you edit any one of them you'll edit all of them. It's actually the same list repeated multiple times. Do this instead:

team_points = [[0]*match_no for _ in range(league_size)]

That will create a separate list of zeroes for each one.