Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am having the below two lists:

first= (1,2,3,4,5,6)

last=(6,5,4,3,2,1)

I want to compare the corresponding values only. I have written the below code, but it is comparing the elements 36 times!

for x in first:

    for y in last:

        if x>y:

            print("first is greater then L2",y)

        elif x==y:

            print("equal")

        else:

            print("first is less then L2",y)

irst= (1,2,3,4,5,6)

last=(6,5,4,3,2,1)

for x in first:

    for y in last:

        if x>y:

            print("first is greater then L2",y)

        elif x==y:

            print("equal")

        else:

            print("first is less then L2",y)

output:

L1 is less then L2 6

L1 is less then L2 5

L1 is less then L2 4

L1 is less then L2 3

L1 is less then L2 2

go dada

L1 is less then L2 6

L1 is less then L2 5

L1 is less then L2 4

L1 is less then L2 3

go dada

L1 is greater then L2 1

L1 is less then L2 6

L1 is less then L2 5

L1 is less then L2 4

go dada

L1 is greater then L2 2

L1 is greater then L2 1

L1 is less then L2 6

L1 is less then L2 5

go dada

L1 is greater then L2 3

L1 is greater then L2 2

L1 is greater then L2 1

L1 is less then L2 6

go dada

L1 is greater then L2 4

L1 is greater then L2 3

L1 is greater then L2 2

L1 is greater then L2 1

go dada

L1 is greater then L2 5

L1 is greater then L2 4

L1 is greater then L2 3

L1 is greater then L2 2

L1 is greater then L2 1

y

I just need to compare the corresponding elements only. There would only be 6 outputs, not 36!

1 Answer

0 votes
by (107k points)
edited by

The first and last values are tuples, not lists in Python.

You can simply use the zip(first, last) to create a list of pairs from the two tuples:

[(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)]

first = (1,2,3,4,5,6)

last = (6,5,4,3,2,1)

for l1,l2 in zip(first,last):

    if l1 < l2:

        print("l1 < l2")

    elif l1 > l2:

        print("l2 > l1")

    elif l1 == l2:

        print("l1 == l2")

Output:

l1 < l2

l1 < l2

l1 < l2

l2 > l1

l2 > l1

l2 > l1

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...