Try and except clauses for appending elements in lists I have a list that can have up to three elements, and I want to append them to three list, because I get this list from another element within a loop. My final goal is to have a dataframe with the data of all elements. I have coded this:

affected_projects_1 = []
affected_projects_2 = []
affected_projects_3 = []

for issue in project:
    affected_projects = issue.affected_projects
    try:
        affected_projects_1.append(affected_projects[0])
    except IndexError:
        affected_projects_1.append('')
    except:
        raise Exception
    try:
        affected_projects_2.append(affected_projects[1])
    except IndexError:
        affected_projects_2.append('')
    except:
        raise Exception
    try:
         affected_projects_3.append(affected_projects[2])
    except IndexError:
        affected_projects_3.append('')
    except:
        raise Exception

 df = pd.DataFrame(zip(affected_projects_1, affected_projects_2, affected_projects_3))


This piece of code seems pretty verbose and almost repetitive (the only thing that changes is the number). How could I make it more compact? Is that even possible without losing readability or using antipatterns (i.e using globals variables). Thanks
except: raise Exception is awful.


It converts all errors to Exception.


This means errors that have nothing to do with Exception like BaseException and KeyboardInterupt are now something they semantically are not.
This also means if you have a KeyError then it's magically the same as any other error.

It doesn't even raise an exception instance, Exception().
There's no need for it, just remove it from your code.




If you weren't appending to different lists then we could see that all we need is a basic for loop.

for proj in issue.affected_projects[:3]:
    affected.append(proj)


Since you have to append to other lists you can zip over them.

for affected, proj in zip(affected_projects, issue.affected_projects):
    affected.append(proj)


Since you need to default to '' you can just extend issue.affected_projects to these values.

affected_projects = [[], [], []]
for issue in project:
    for affected, proj in zip(
        affected_projects,
        issue.affected_projects + 3*['']
    ):
        affected.append(proj)


We can remove the need for affected.append by moving the zip up one loop.

affected_projects = zip(*(
    (issue.affected_projects + 3*[''])[:3]
    for issue in project
))
pd.DataFrame(zip(*affected_projects))


Since you are ziping affected_projects and you're zipping issue.affected_projects you don't really need to zip at all.

df = pd.DataFrame(
    (issue.affected_projects + 3*[''])[:3]
    for issue in project
)