Iterating through a list and using ltems of other lists
<pre><code>l = ['hello','hi']
a=[1,2,3,4]
b=[4,5,6,7]
for i in l:
 func(x=a[index],y=b[index])
</code></pre>

<p>Now when I'm iterating through l , in the first iteration i want to use first a[0]and b[0] for a function and then use a[1] and b[1] for the same function</p>

<p>And in the second iteration of l,i want to use first a[2]and b[2] for the function and then use a[3] and b[3] for the same function.</p>

<p>Any recommendations would be appreciated.</p>

<p>You can use the index method to find the index of the element of the list you are iterating through. Using that index you can find the element from the list you want to pass to the function.</p>

<pre><code>l = ['hello','hi']
a=[1,2,3,4]
b=[4,5,6,7]

def demo(x, y):
    print x, y

for i in l:
    print i
    idx = 2*(l.index(i))
    demo(x=a[idx],y=b[idx])
    demo(x=a[idx+1],y=b[idx+1])
</code></pre>

<p>Instead of calculating the index for <code>a</code> and <code>b</code> inside the call to <code>demo()</code>, I prefer to calculate it before hand. Because, each calculation has complexity of <code>O(1)</code>, and if I am doing the same inside the call to <code>demo</code> (i.e. if I'm doing <code>demo(x=a[2*(l.index(i))],y=b[2*(l.index(i))])</code>) , then I am ending up calculating the index twice which results a complexity of <code>O(2)</code>. In the same way I am accessing the list <code>l</code> twice, which also adds overhead to complexity calculation. Therefore, calculating the index beforehand, accesses the list <code>l</code> once and reduces the complexity by 2 times for each call to <code>demo</code> thus by 4 times.</p>

python python-2.7