Python Forum
IndexError: list index out of range
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
IndexError: list index out of range
#1
N = 3

# Returns true if square is magic
# square, else returns false.
def is_magic(square):
    # calculate the sum of
    # the prime diagonal
    sum = 0
    for i in range(0, N):
        sum += square[i][i]

        # For sums of Rows
    for i in range(0, N):
        rowSum = 0
        for j in range(0, N):
            rowSum += square[i][j]

            # check if every row sum is
        # equal to prime diagonal sum
        if (rowSum != sum):
            return False

    # For sums of Columns
    for i in range(0, N):
        columnSum = 0
        for j in range(0, N):
            columnSum += square[j][i]

            # check if every column sum is
        # equal to prime diagonal sum
        if (sum != columnSum):
            return False

    return True

str_input = input("write a squence of nine numbers")
str_list = str_input.split()

square = []
for i in range(0, N):
    square.append([])
    for j in range(0, N):
        square[i].append(int(str_list[j + i * N]))

if (is_magic(str_list)):
    print("This is Magic Square")
else:
    print("This is Not a magic Square")
The error I keep getting is in the line where it says
square[i].append(int(str_list[j + i * N]))

I am trying to create a program that asks user for sequence of 9 numbers and determines if they are nagic square or not.
Reply


Messages In This Thread
IndexError: list index out of range - by abdullahali - Jan-16-2019, 10:24 PM
RE: IndexError: list index out of range - by nilamo - Jan-16-2019, 10:37 PM
RE: IndexError: list index out of range - by buran - Jan-17-2019, 07:54 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to fix list index out of range longmen 26 6,223 Apr-27-2022, 05:46 PM
Last Post: deanhystad
  list index out of range OliverG 3 2,379 Sep-03-2021, 12:04 AM
Last Post: itsmycode
  Index List a04j 2 2,951 Jul-10-2021, 01:14 PM
Last Post: BashBedlam
  List index out of range when turning CSV into dict ranbarr 15 6,580 May-12-2021, 10:38 AM
Last Post: ranbarr
  List vs index: Frederico_Caldas 5 3,665 Jul-03-2020, 10:55 AM
Last Post: DeaD_EyE
  To find the index of the first occurrence of the key in the provided list Angry_bird89 4 3,304 Jun-20-2020, 06:53 PM
Last Post: Angry_bird89
  list index out of range mcgrim 2 2,943 May-25-2019, 07:44 PM
Last Post: mcgrim
  String index out of range felie04 2 5,578 Aug-17-2018, 11:18 PM
Last Post: felie04
  Accessing data in zip - Index out of range pythoneer 24 12,956 Mar-15-2018, 06:19 PM
Last Post: buran
  "List index out of range" for output values pegn305 3 5,346 Nov-26-2017, 02:20 PM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020