CSupport
CSupport

Reputation: 3

Comparing each item in list to Other item in other list Python

illustration of comparison

i got stuck on this code, can you help me?

a = [1, 2, 3]
b = [4, 5, 6]

item = []
item.append(a)
item.append(b)

for i in range(len(item)):
    for j in range(len(item[i])):
        print('{} <= {}'.format(item[i][j], item[i+1][j]))

Upvotes: 0

Views: 39

Answers (3)

EnriqueBet
EnriqueBet

Reputation: 1473

According to your illustration and assuming that the number of elements is equal on a and b, I believe the approach you are looking for is:

a = [1, 2, 3]
b = [4, 5, 6]

for i in range(len(a)):
    print(f"{a[i]} <= {b[i]}")

But if you want to obtain the result of the comparisson, you can do:

a = [1, 2, 3]
b = [4, 5, 6]

for i in range(len(a)):
    print(f"{a[i]} <= {b[i]} : {a[i] <=b [i]}")

Hopefully this will help you! :D

Upvotes: 0

Joshua Hall
Joshua Hall

Reputation: 342

If you do it for three lists, It would look like this:

for x,y,z in zip(a,b,c):
    print(f"{x} <= {y} <= {z}")

Output:

1 <= 4 <= 7
2 <= 5 <= 8
3 <= 6 <= 9

Upvotes: 2

Austin
Austin

Reputation: 26039

You can use zip to iterate over lists in parallel:

for x, y in zip(a, b):
    print(f'{x} <= {y}')

# 1 <= 4
# 2 <= 5
# 3 <= 6

Upvotes: 2

Related Questions