I have a list that will sometimes hold a single value, sometimes 2 or 3 values. I am assigning each of the values to a variable. If there is no value for the assigned position of the list, I want it to be a empty variable. Is there any way I can make this more efficient?
split = line.split(',') try: var1 = split[0] except IndexError: var1 = None try: var2 = split[1] except IndexError: var2 = None try: var3 = split[2] except IndexError: var3 = None
dict. can't you usedictto store these values instead of storing these in separate variables?var1, var2, var3 = (split + [None] * 3)[:3].lineis a string,split[0]will always exist. So is there a reason you're expecting anIndexError? For example,''.split(',')->['']