Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
index errors
#1
Can someone please tell what I am doing wrong??...I am continually getting an index error. I have a 4x2x3 matrix (lists) and I am trying to first create a list containing three lists and then as a final step I would like to reduce this to one list....I test lengths out in the command line so I do not understand why I am getting these index errors....
what would the solution look like in list comprehension?

thanks

import random
def m():
	c = []; tmpa = []; tmpb = []
	c.append([[[random.randint(0,4) for i in range(2)] for k in range(4)] for i in range(3)])
	for i in range(2):
		tmpa = []
		for j in range(4):
			tmpb = []
			for k in range(2):
				p = sum(c[i][j][k])
			tmpb.append(p)
		tmpb.append(tmpa)
	return(c)
Error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/pi/myPython/test.py", line 10, in m p = sum(c[i][j][k]) IndexError: list index out of range
Reply
#2
What is your goal? This is one of those times we'd rather help you toward your goal than try to help with the specific thing you're stuck on because you might be taking a messy approach to the problem.

There are a few things about your code that stand out. tmpa and tmpb don't need to be declared before the loop since you reassign the variables inside the loop(s) anyway. Really though those lists are only written to, never read from, so they can be removed entirely. You return c in spite of never mutating it after it's c. Your innermost loop reassigns a variable in an odd way that likely isn't intentional.

So, what's your goal?
Reply
#3
Thank you for your response and my goal is to understand the dimension errors I am getting....The exercise is I would like to take the elements of the matrix c and add them to get a single list....I would like to add the list c[0][0] to c[1][0] to c[2][0] and this would be element 0 in the list....then add c[0][2] to c[1][2] to c[2][2]...and so on ... eventually it becomes a list....

Hope this helps...
Thank you
Reply
#4
What you want to do is called flattening
import random

m = [[[random.randint(0,4) for i in range(2)] for k in range(4)] for i in range(3)]
print(m)

def flatten(matrix):
    flat = []
    for dim1 in matrix:
        for dim2 in dim1:
            for element in dim2:
                flat.append(element)
    return flat

print(flatten(m))
and that flattening can be coded as one line
def flatten(matrix):
    return [element for dim1 in matrix for dim2 in dim1 for element in dim2]
Reply


Forum Jump:

User Panel Messages

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