How to run two loop simeltanously in one loop in python
<p>Is there any way available to put two loops in one? I have:</p>

<pre><code>for getFeature in layerNameValueGetObj.getFeatures():
    for setFeature in layerNameValueSetObj.getFeatures():
</code></pre>

<p>I want to run <code>layerNameValueGetObj.getFeatures()</code> and <code>layerNameValueSetObj.getFeatures()</code> under one loop. How can I do this?</p>

<p>I don't want to nest them, I want to get both loop columns at a time.</p>

<p><code>zip_longest</code> will iterate until all lists are consumed.  For <code>zip</code> the results are truncated to the shortest iterator.</p>

<pre><code>from itertools import zip_longest    

for get_feature, set_feature in zip_longest(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()):
    print(get_feature, set_feature)
</code></pre>

<p>Here's an example of both <code>zip</code> and <code>zip_longest</code> output:</p>

<p>DummyObject Setup code:</p>

<pre><code>class DummyObject:
    def __init__(self, reversed=False, length=10):
        self.reversed = reversed
        self.length = length

    def getFeatures(self):
        if self.reversed:
            g = reversed(range(self.length))
        else:
            g = range(self.length)
        return g

layerNameValueGetObj = DummyObject(False, length=10)
layerNameValueSetObj = DummyObject(True, length=15)
</code></pre>

<p>Run with <code>zip_longest</code>:</p>

<pre><code>from itertools import zip_longest    

for get_feature, set_feature in zip_longest(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()):
    print(get_feature, set_feature)
</code></pre>

<p>zip_longest result:</p>

<pre><code>0 14
1 13
2 12
3 11
4 10
5 9
6 8
7 7
8 6
9 5
None 4
None 3
None 2
None 1
None 0
</code></pre>

<p>Run with <code>zip</code>:</p>

<pre><code>for get_feature, set_feature in zip(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()):
        print(get_feature, set_feature)
</code></pre>

<p>zip result:</p>

<pre><code>0 14
1 13
2 12
3 11
4 10
5 9
6 8
7 7
8 6
9 5
</code></pre>

<p>So in this case where layerNameValueGetObj has 10 features and layerNameValueSetObj has 15 features, with <code>zip</code> only a total of 10 features will be processed with the remaining 5 layerNameValueSetObj features truncated.</p>

<p>With <code>zip_longest</code>, the shorter iterator will return <code>None</code> where no elements exist. (as seen above)</p>

python