0

I am essentially trying to work out if a specified index is a list or not. I have a list embedded into an index.

This is what I have so far

    if len(hashTable[hashed-1])>1:
        hashTable[hashed-1].append(inVal)
    else:
        tempTable = [hashTable[hashed-1], inVal]  
        hashTable[hashed-1] = tempTable
        print(inVal,hashed)
        print(hashTable)

The output of the list is: (the 0's an 10 are irrelevant)

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, [1, 3], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10]

The error is:

    if len(hashTable[hashed-1])>1:
TypeError: object of type 'int' has no len()
3
  • hashTable[hashed-1] is an int, not a list, hence the error, try if isinstance(hashTable[hashed-1], list) and len(hashTable[hashed-1]) > 1 Commented Oct 3, 2019 at 0:30
  • 1
    Look at my comment or the answer given by @Massifox Commented Oct 3, 2019 at 0:34
  • Thank you, the if isinstance(hashTable[hashed-1], list) worked
    – Kewmolk
    Commented Oct 3, 2019 at 0:36

1 Answer 1

2

You must use isinstance, to check if your object is a list type, as follows:

isinstance(hashTable[hashed-1], list)

in your case:

if isinstance(hashTable[hashed-1], list) and len(hashTable[hashed-1]) > 1

Python uses lazy evaluation, to evaluate the condition in this if-statement. So len(hashTable[hashed-1]) will be called only when isinstance(hashTable[hashed-1], list) is True.

1
  • Thank you. Didn't realise it was that simple :)
    – Kewmolk
    Commented Oct 3, 2019 at 0:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.