Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop in two lists

Tags:

python

I have these lists:

list1 = [3, 5, 2, 1, 9]
list2 = [6, 9, 1, 2, 4]
list3 = []
list4 = []

and I want to pass these formula:

x = a/b
y = 1/b

in which a is every value in list1 and b is every value in list2 and append the result of calculations into two empty lists - list3 and list4.

This is what I have but it's a disaster haha :(

u = 0
while u<len(list1):
    for a in list1:
        for b in list2:
            x = a/b
            y = 1/b
            u+=1
            list3.append(x,)
            list4.append(y,)

Anyone can help me with this?

like image 262
DarsAE Avatar asked May 27 '26 14:05

DarsAE


2 Answers

Here is a oneliner:

>>> list3,list4 = zip(*[(a/b,1/b) for a,b in zip(list1,list2)])
>>> list3
(0, 0, 2, 0, 2)
>>> list4
(0, 0, 1, 0, 0)

The output are tuples. But they can be easily converted to list.

Oh. It may be made even more memory efficient by using generator expression instead of list comprehension:

>>> zip(*((a/b,1/b) for a,b in zip(list1,list2)))
like image 52
ovgolovin Avatar answered Jun 02 '26 13:06

ovgolovin


for a, b in zip(list1, list2):
    x = a/b
    y = 1/b
    list3.append(x)
    list4.append(y)

This is assuming you meant you wanted to use the lists pair-wise. If instead you meant you wanted every possible pairing of the lists, then:

for a in list1:
    for b in list2:
        x = a/b
        y = 1/b
        list3.append(x)
        list4.append(y)
like image 44
Ned Batchelder Avatar answered Jun 02 '26 14:06

Ned Batchelder