0

I am trying to read a file and check to see that every number is present, all unique. I tried checking the equality of the length of the list and the length of the set. I get this error TypeError: unhashable type: 'list' Do i have to convert the list to something else?

Here is code

def readMatrix(filNam):
    matrixList = []
    numFile = open(filNam, "r")
    lines = numFile.readlines()
    for line in lines:
        line = line.split()
        row = []
        for i in line:
            row.append(int(i))
        matrixList.append(row)
    return matrixList

def eachNumPresent(matrix):
    if len(matrix) == len(set(matrix)):
        return True
    else:
        return False
2
  • can you paste your exact stacktrace? Your stacktrace does not necessarily correspond to the code you have shown Commented Oct 22, 2014 at 18:50
  • 1
    Do not write if foo: return True; else: return False; write just return foo. Commented Oct 22, 2014 at 18:51

3 Answers 3

2

A list cannot be an element of a set, so you cannot pass a list of lists to set(). You need to unravel the list of lists to a single list, then pass to set (so integers are your set elements).

unraveled = [x for line in matrix for x in line]
return len(unraveled) == len(set(unraveled))
Sign up to request clarification or add additional context in comments.

Comments

1

Your matrix is a list of lists. When you write set(matrix), Python tries to create a set of all rows of the matrix. Your rows are lists, which are mutable and unhashable.

What you want is a set of all values in the matrix. You can count it with an explicit loop:

all_values = set()
for row in matrix:
  all_values.update(row)
# here all_values contains all distinct values form matrix

You could also write a nested list comprehension:

all_values = set(x for row in matrix for x in row)

Comments

0

"set" doesn't work on list of lists but works fine on list of tuples. So use the below code :

matrixList.append(tuple(row))

instead of :

matrixList.append(row)

4 Comments

thanks! that fixed the problem, but i was wondering how could i check equality of these three things should i convert the last one to look like the first two? [65, 65, 65, 65, 65] [65, 65, 65, 65, 65] (65, 65)
You can't compare a list with a tuple, they are of different type. You have to have them in same type, either list or tuple, for comparison.
I converted them all to tuple but the last one only has two elements so it doesnt compare the three to true. I want it to be true if all the numbers are the same even if the last one has two elements
Use matrixList.append(tuple(set(row))) instead of matrixList.append(row). It should solve your problem.

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.