{"id":10431,"date":"2023-07-18T09:35:33","date_gmt":"2023-07-18T04:05:33","guid":{"rendered":"https:\/\/www.csestack.org\/?p=10431"},"modified":"2023-07-18T09:45:00","modified_gmt":"2023-07-18T04:15:00","slug":"sum-diagonal-elements-matrix-python-code","status":"publish","type":"post","link":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/","title":{"rendered":"[Solved] Sum of Diagonal Elements in Matrix in Python Code"},"content":{"rendered":"\n<p>We can save the matrix as a list of lists in Python i.e. two dimensional list. To find the sum of diagonal elements, we are using a <a href=\"https:\/\/www.csestack.org\/python-list\/\">Python list<\/a> to save the matrix elements and <a href=\"https:\/\/www.csestack.org\/python-for-while-loop-else\/\">Python for-loop<\/a> to traverse diagonal elements.<\/p>\n\n\n\n<p>This coding question has been asked in many interviews (especially for the freshers). The difficulty level is easy.<\/p>\n\n\n\n<p>Check the following Python code. It&#8217;s very simple and self-descriptive.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">matrix = [[1, 4, 5],\n  \t\t[5, 5, 7],\n  \t\t[4, 1, 3]]\n\nsum = 0\nfor i in range(len(matrix)):\n  sum = sum+matrix[i][i] \n\nprint(f&quot;Sum of diagonal elements in matrix = {sum}&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Sum of diagonal elements in matrix = 9<\/pre>\n\n\n\n<p><strong>Note:<\/strong> We can only find the sum of diagonal elements in Python when the matrix is square. A square matrix is a matrix that has the same number of rows and columns. <\/p>\n\n\n\n<p>You can modify the above code to check whether the given matrix is square or not before finding the sum of diagonal elements.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:false,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">matrix = [[1, 4, 5],\n  \t\t[5, 5, 7],\n  \t\t[4, 1, 3]]\n\nif len(matrix) != len(matrix[0]):\n  print(&quot;Matrix is not a square matrix.&quot;)\nelse:\n  sum = 0\n  for i in range(len(matrix)):\n    sum = sum+matrix[i][i] \n  print(f&quot;Sum of diagonal elements in matrix = {sum}&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Complexity:<\/strong><\/p>\n\n\n\n<p>Let&#8217;s say the size of the matrix is <code>n*n<\/code> where the number of rows and columns is the same as <code>n<\/code>.<\/p>\n\n\n\n<p>In the above code, we are traversing each element in the rows (or columns) once, using a single for loop. So the complexity of this algorithm is <code>O(n)<\/code>. <\/p>\n\n\n\n<p>If you want to improve your coding skills, <a href=\"https:\/\/www.csestack.org\/interview-coding-questions-programming-language\/\">practice solving similar coding questions<\/a>.<\/p>\n\n\n\n<p>Happy Coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How to find the sum of diagonal elements in matrix in Python code. Asked in coding interview.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,73],"tags":[72],"class_list":["post-10431","post","type-post","status-publish","format-standard","hentry","category-code","category-python","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>[Solved] Sum of Diagonal Elements in Matrix in Python Code<\/title>\n<meta name=\"description\" content=\"How to find the sum of diagonal elements in matrix in Python code. Asked in coding interview.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Sum of Diagonal Elements in Matrix in Python Code\" \/>\n<meta property=\"og:description\" content=\"How to find the sum of diagonal elements in matrix in Python code. Asked in coding interview.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/\" \/>\n<meta property=\"og:site_name\" content=\"CSEstack\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/aniruddha.ca\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/aniruddha.ca\" \/>\n<meta property=\"article:published_time\" content=\"2023-07-18T04:05:33+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-07-18T04:15:00+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.csestack.org\/wp-content\/uploads\/2024\/01\/csestack-blog.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1280\" \/>\n\t<meta property=\"og:image:height\" content=\"720\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Aniruddha Chaudhari\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@ani_chaudhari\" \/>\n<meta name=\"twitter:site\" content=\"@ani_chaudhari\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Aniruddha Chaudhari\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"1 minute\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/\"},\"author\":{\"name\":\"Aniruddha Chaudhari\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"headline\":\"[Solved] Sum of Diagonal Elements in Matrix in Python Code\",\"datePublished\":\"2023-07-18T04:05:33+00:00\",\"dateModified\":\"2023-07-18T04:15:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/\"},\"wordCount\":200,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"keywords\":[\"Python\"],\"articleSection\":[\"Code\",\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/\",\"name\":\"[Solved] Sum of Diagonal Elements in Matrix in Python Code\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#website\"},\"datePublished\":\"2023-07-18T04:05:33+00:00\",\"dateModified\":\"2023-07-18T04:15:00+00:00\",\"description\":\"How to find the sum of diagonal elements in matrix in Python code. Asked in coding interview.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/sum-diagonal-elements-matrix-python-code\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.csestack.org\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Sum of Diagonal Elements in Matrix in Python Code\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#website\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/\",\"name\":\"CSEstack\",\"description\":\"Computer Science &amp; Programming Portal\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.csestack.org\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/www.csestack.org\\\/#\\\/schema\\\/person\\\/634ef1a9c4f38b0d340c6d45fa771218\",\"name\":\"Aniruddha Chaudhari\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"url\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"contentUrl\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\",\"width\":634,\"height\":634,\"caption\":\"Aniruddha Chaudhari\"},\"logo\":{\"@id\":\"https:\\\/\\\/www.csestack.org\\\/wp-content\\\/uploads\\\/2019\\\/03\\\/Aniruddha-Chaudhari.jpg\"},\"description\":\"I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.\",\"sameAs\":[\"https:\\\/\\\/www.csestack.org\",\"https:\\\/\\\/www.facebook.com\\\/aniruddha.ca\",\"pythonwithani\",\"https:\\\/\\\/www.linkedin.com\\\/in\\\/aniruddha28\\\/\",\"https:\\\/\\\/x.com\\\/ani_chaudhari\",\"https:\\\/\\\/www.youtube.com\\\/channel\\\/UCw0a__B0eJsvCujkSIfLTAA\"],\"url\":\"https:\\\/\\\/www.csestack.org\\\/author\\\/anicse\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Sum of Diagonal Elements in Matrix in Python Code","description":"How to find the sum of diagonal elements in matrix in Python code. Asked in coding interview.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Sum of Diagonal Elements in Matrix in Python Code","og_description":"How to find the sum of diagonal elements in matrix in Python code. Asked in coding interview.","og_url":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/","og_site_name":"CSEstack","article_publisher":"https:\/\/www.facebook.com\/aniruddha.ca","article_author":"https:\/\/www.facebook.com\/aniruddha.ca","article_published_time":"2023-07-18T04:05:33+00:00","article_modified_time":"2023-07-18T04:15:00+00:00","og_image":[{"width":1280,"height":720,"url":"https:\/\/www.csestack.org\/wp-content\/uploads\/2024\/01\/csestack-blog.jpg","type":"image\/jpeg"}],"author":"Aniruddha Chaudhari","twitter_card":"summary_large_image","twitter_creator":"@ani_chaudhari","twitter_site":"@ani_chaudhari","twitter_misc":{"Written by":"Aniruddha Chaudhari","Est. reading time":"1 minute"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/#article","isPartOf":{"@id":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/"},"author":{"name":"Aniruddha Chaudhari","@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"headline":"[Solved] Sum of Diagonal Elements in Matrix in Python Code","datePublished":"2023-07-18T04:05:33+00:00","dateModified":"2023-07-18T04:15:00+00:00","mainEntityOfPage":{"@id":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/"},"wordCount":200,"commentCount":0,"publisher":{"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"keywords":["Python"],"articleSection":["Code","Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/","url":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/","name":"[Solved] Sum of Diagonal Elements in Matrix in Python Code","isPartOf":{"@id":"https:\/\/www.csestack.org\/#website"},"datePublished":"2023-07-18T04:05:33+00:00","dateModified":"2023-07-18T04:15:00+00:00","description":"How to find the sum of diagonal elements in matrix in Python code. Asked in coding interview.","breadcrumb":{"@id":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.csestack.org\/sum-diagonal-elements-matrix-python-code\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.csestack.org\/"},{"@type":"ListItem","position":2,"name":"[Solved] Sum of Diagonal Elements in Matrix in Python Code"}]},{"@type":"WebSite","@id":"https:\/\/www.csestack.org\/#website","url":"https:\/\/www.csestack.org\/","name":"CSEstack","description":"Computer Science &amp; Programming Portal","publisher":{"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.csestack.org\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.csestack.org\/#\/schema\/person\/634ef1a9c4f38b0d340c6d45fa771218","name":"Aniruddha Chaudhari","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","url":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","contentUrl":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg","width":634,"height":634,"caption":"Aniruddha Chaudhari"},"logo":{"@id":"https:\/\/www.csestack.org\/wp-content\/uploads\/2019\/03\/Aniruddha-Chaudhari.jpg"},"description":"I am a Python enthusiast who loves Linux and Vim. I hold a Master of Computer Science degree from NIT Trichy and have 10 years of experience in the IT industry, focusing on the Software Development Lifecycle from Requirements Gathering, Design, Development to Deployment. I have worked at IBM, Ericsson, and NetApp, and I share my knowledge on CSEstack.org.","sameAs":["https:\/\/www.csestack.org","https:\/\/www.facebook.com\/aniruddha.ca","pythonwithani","https:\/\/www.linkedin.com\/in\/aniruddha28\/","https:\/\/x.com\/ani_chaudhari","https:\/\/www.youtube.com\/channel\/UCw0a__B0eJsvCujkSIfLTAA"],"url":"https:\/\/www.csestack.org\/author\/anicse\/"}]}},"_links":{"self":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/10431","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/comments?post=10431"}],"version-history":[{"count":3,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/10431\/revisions"}],"predecessor-version":[{"id":10439,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/posts\/10431\/revisions\/10439"}],"wp:attachment":[{"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/media?parent=10431"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/categories?post=10431"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.csestack.org\/wp-json\/wp\/v2\/tags?post=10431"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}