Type of variable changes based on access?
<p>I have a directed graph structure consisting of nodes and edges both of which subclass an Event parent class. Depending on external events, edges can either be active or inactive. I then find all the directed paths from a given node to the root node, but I really only care about the nodes along the way, not the edges. For instance, to convert from a set of edges to a set of nodes I use:</p>

<pre><code>&gt;&gt;&gt; paths
[[&lt;Edge F&gt;, &lt;Edge B&gt;]]
&gt;&gt;&gt; lst = [set(map(lambda e: e.tail, path)) for path in paths]
</code></pre>

<p>where path is a list of edges. This is what confuses me: when I go to check the contents of <code>lst</code>, it changes depending on how I access it</p>

<pre><code>&gt;&gt;&gt; lst
[set([&lt;Node 2&gt;, &lt;Node 1&gt;])]
&gt;&gt;&gt; [type(n) for n in path for path in lst]
[&lt;class 'libs.network.Edge'&gt;, &lt;class 'libs.network.Edge'&gt;]
&gt;&gt;&gt; [type(n) for n in lst[0]]
[&lt;class 'libs.network.Node'&gt;, &lt;class 'libs.network.Node'&gt;]
</code></pre>

<p>Why aren't these two ways of accessing the type information the same?</p>

<p>You have your list comprehension order wrong. Nested loops are listed from <em>left to right</em>.</p>

<p>So the expression</p>

<pre><code>[type(n) for n in path for path in lst]
</code></pre>

<p>is executed as</p>

<pre><code>for n in path:
    for path in lst:
        type(n)
</code></pre>

<p>so <code>n</code> is taken from some random pre-assigned <code>path</code> variable you had before, and it is <em>that variable</em> that contains <code>Edge</code> instances. Those objects have <em>nothing</em> to do with the contents of <code>lst[0]</code> you loop over in your other expression.</p>

<p>You probably wanted to do this the other way around:</p>

<pre><code>[type(n) for path in lst for n in path]
</code></pre>

<p>so that <code>path</code> is actually set from <code>lst</code> <em>before</em> you iterate over it.</p>

python types list-comprehension