Python List Index Out of Range nested list -


i have nested list main_category, each nested list unicode string of business names. first 5 lines of nested lists below:

[[u'medical centers', u'health , medical'], [u'massage', u'beauty , spas'], [u'tattoo', u'beauty , spas'], [u'music & dvds', u'books, mags, music , video', u'shopping'], [u'food', u'coffee & tea']] 

so want first element of every list, , have tried list comprehension, zip, nothing works.

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

but 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 don't know wrong this. help? much!

the error indicates one/some of sublists in full list empty lists. need handle that. can put ternary operator in list comprehension substitute default value when list empty , index first item when isn't:

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

you can replicate fix zip using it's itertools variant izip_longest allows set fillvalue:

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

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -