Home > Enterprise >  Python: List index Out of Range Error when list indexing
Python: List index Out of Range Error when list indexing

Time:11-13

I have a list of lists property_lists which is structured as follows:

property_lists = [['Semi-Detached', '|', '', '2', '|', '', '2'], ['Detached', '|', '', '5', '|', '', '3'], ['Detached', '|', '', '5', '|', '', '5']]

and so on.

I am attempting list indexing in order to put all the elements into separate lists of their own.

For example:

typeOfProperty = [item[0] for item in property_lists]

returns

['Semi-Detached', 'Detached', 'Detached']

However, the below results in an index list out of range error:

bedrooms = [item[3] for item in property_lists]

But I don't understand why as each 'sub' list has 7 elements?

To be clear, i am trying to output:

['2', '5', '5']

CodePudding user response:

First can you please give example, of what you want in the output?

If you want the output like the below:

propertyList1 = ['Semi-Detached', '|', '', '2', '|', '', '2']
propertyList2 = ['Detached', '|', '', '5', '|', '', '3']
propertyList3 = ['Detached', '|', '', '5', '|', '', '5']

then Here's the solution:

property_lists = [['Semi-Detached', '|', '', '2', '|', '', '2'], ['Detached', '|', '', '5', '|', '', '3'], ['Detached', '|', '', '5', '|', '', '5']]
    
propertyList1 = [items for items in property_lists[0]]
propertyList2 = [items for items in property_lists[1]]
propertyList3 = [items for items in property_lists[2]]

So what I am doing here is, I am taking the property_lists every index and creates its own list using list comprehension

You are taking the only first index of the item in your question, that's why it is the result list contains only "Semi-Detached" and "Detached" values.

AND

your second question is about the list index out of range, That is happening because you are running the for loop on the property_lists, and item variable will store the value that is coming from the property_lists, so you cannot access the element with an index of the item. you can access the index-wise items after creating the separate lists like I created in the code.

CodePudding user response:

The problem is with your full data that referred in your comment https://pastecode.io/s/pg56vfyk.

One of the elements of property_lists has the the length of 1. That is property_lists[8] = ['Land for sale']. You should have a check like this.

bedrooms =  [item[3] if len(item) > 2 else 0 for item in p]

Similar way for other indices > 0.

  • Related