Parker Parker - 11 months ago 72
Python Question

Python List Index Out of Range nested list

I have a nested list main_category, each nested list is a unicode string of business names. The first five lines of the nested lists are below:

[[u'Medical Centers', u'Health and Medical'],
[u'Massage', u'Beauty and Spas'],
[u'Tattoo', u'Beauty and Spas'],
[u'Music & DVDs', u'Books, Mags, Music and Video', u'Shopping'],
[u'Food', u'Coffee & Tea']]

So I want to get the first element of every list, and I have tried list comprehension, zip, but nothing works.

new_cate = [d[0] for d in main_category]
lst = zip(*main_category)[0]

But all of them give me

IndexErrorTraceback (most recent call last)
<ipython-input-49-4a397c8e62fd> in <module>()
----> 1 lst = zip(*main_category)[0]
IndexError: list index out of range

I really don't know what is wrong with this. So could anyone help? Thanks so much!

Answer Source

The error indicates one/some of the sublists in the full list are empty lists. You need to properly handle that. You can put a ternary operator in the list comprehension to substitute a default value when the list empty is and index the first item when it isn't:

default = ''
new_cate = [d[0] if d else default for d in main_category]
#                ^^^^-> test if list is truthy

You can also replicate this fix for zip by using it's itertools variant izip_longest which allows you to set a fillvalue:

from itertools import izip_longest

default = ''
lst = list(izip_longest(*main_category, fillvalue=default))[0]