List comprehension including elements of different sizes
<p>I have the following <code>for/if-elif-else</code> loop which extracts department information from tuples <code>t</code> in a list, based on the size of <code>t[0]</code>:</p>

<pre><code>for t in filt:
    if len(t[0]) == 1:
        pass
    elif len(t[0]) == 2:
        if 'organization' in t[0][0]['affiliation']:
            depA = t[0][0]['affiliation']['organization']
        else: depA = 'Not Available'

        if 'organization' in t[0][1]['affiliation']:
            depB = t[0][1]['affiliation']['organization']
        else: depB = 'Not Available'

        depC = 'None'


    else:
        if 'organization' in t[0][0]['affiliation']:
            depA = t[0][0]['affiliation']['organization']
        else: depA = 'Not Available'

        if 'organization' in t[0][1]['affiliation']:
            depB = t[0][1]['affiliation']['organization']
        else: depB = 'Not Available'

        if 'organization' in t[0][2]['affiliation']:
            depC = t[0][1]['affiliation']['organization']
        else: depC = 'Not Available'
</code></pre>

<p>Is there a way to do things like this in a single line even though the sizes of <code>t[0]</code> may be different. The reason I ask is that I may be incorrectly assuming that there are a maximum of 3 departments in <code>t[0]</code> when there in fact may be more and I'd like to save lines of code if possible.</p>

<p>In essence what I'd really like is something like having a list of a sensible number of the maximum possible departments based on my data ie 6 and then have something like</p>

<pre><code>for t in filt:
    depA = [t[0][0]['affiliation']['organization'] if 'organization' in t[0][0]['affiliation'] else 'Not Available']
</code></pre>

<p>which is fine because <code>t[0]</code> is always of size at least 1. But here's where it gets tricky and the line of code below won't make pythonic sense:</p>

<pre><code>depB = [t[0][1]['affiliation']['organization'] if t[0][1] exists AND 'organization' in t[0][1]['organization'] else 'Not Available']
</code></pre>

<p>and so forth...</p>

<p>If I haven't worded the question title right, please change as required! Thanks!</p>

<p>Turns out the following line of code will work, checking the index against the size of the list in question and using if else in the list comprehension:</p>

<pre><code>depB = [t[0][1]['affiliation']['organization'] if 2&lt;=len(t[0]) and 'organization' in t[0][1]['affiliation'] else 'Not Available' for t in filt]
</code></pre>

python