Build 2 lists in one go while reading from file, pythonically
<p>I'm reading a big file with hundreds of thousands of number pairs representing the edges of a graph. I want to build 2 lists as I go: one with the forward edges and one with the reversed. </p>

<p>Currently I'm doing an explicit <code>for</code> loop, because I need to do some pre-processing on the lines I read. However, I'm wondering if there is a more pythonic approach to building those lists, like list comprehensions, etc. </p>

<p>But, as I have 2 lists, I don't see a way to populate them using comprehensions without reading the file twice.</p>

<p>My code right now is:</p>

<pre><code>with open('SCC.txt') as data:
    for line in data:
        line = line.rstrip()
        if line:
            edge_list.append((int(line.rstrip().split()[0]), int(line.rstrip().split()[1])))
            reversed_edge_list.append((int(line.rstrip().split()[1]), int(line.rstrip().split()[0])))
</code></pre>

<p>You <em>can't</em> create two lists in one comprehension, so, instead of doing the same operations twice on the two lists, one viable option would be to initialize one of them and then create the second one by reversing each entry in the first one. That way you don't iterate over the file twice.</p>

<p>To that end, you could create the first list <code>edge_list</code> with a comprehension (not sure why you called <code>rsplit</code> <em>again</em> on it):</p>

<pre><code>edge_list = [tuple(map(int, line.split())) for line in data]
</code></pre>

<p>And now go through each entry and reverse it with <code>[::-1]</code> in order to create its reversed sibling <code>reverse_edge_list</code>. </p>

<p><em>Using mock data</em> for <code>edge_list</code>:</p>

<pre><code>edge_list = [(1, 2), (3, 4), (5, 6)]
</code></pre>

<p>Reversing it could look like this:</p>

<pre><code>reverse_edge_list = [t[::-1] for t in edge_list]
</code></pre>

<p>Which now looks like:</p>

<pre><code>reverse_edge_list
[(2, 1), (4, 3), (6, 5)]
</code></pre>

python list python-3.x