user15552191
user15552191

Reputation:

how do I compare subsequently integers in two lists?

I have two lists nums1 = [1,5,10,44,4] and nums2 = [5,3,10,55,3]; if I wanted to compare the first numbers of both lists with each other, then the second numbers, then the third numbers, and so on... i.e. 1 with 5, 5 with 3, 10 with 10, etc.

How can I do this?

My initial thought is to use two for loops, but then I end up comparing all of the list with each integer, when all I am after is to compare the one integer from one list with another integer from the other list.

Upvotes: 0

Views: 310

Answers (5)

MrBhuyan
MrBhuyan

Reputation: 161

x, y = [1,5,10,44,4], [5,3,10,55,3]

# If both list have same length
for i in range(len(x)):
  # Compare here with the index
  if x[i] == y[i]:
    # Do something
    print(x[i], "is same in both lists")

Upvotes: 0

Khay Leng
Khay Leng

Reputation: 451

nums1 = [1,5,10,44,4]
nums2 = [5,3,10,55,3]

result = [nums1[x] > nums2[x] for x in range(len(nums1))]

I assume both lists have equal length.

And the result: elements in nums1 > elements in nums2

[False, True, False, False, True]

Upvotes: 0

David Meu
David Meu

Reputation: 1545

Just do:

nums1 = [1,5,10,44,4]
nums2 = [5,3,10,55,3]

nums_res = [max(l1, l2) for l1, l2 in zip(nums1,nums2)]

Upvotes: 0

DarrylG
DarrylG

Reputation: 17156

Using zip:

for a, b in zip(nums1, nums2):
    # zip loops through both lists in parallel
    compare = "less" if a < b else "equal" if a == b else "greater"  # Example compare
    print(f"{a} {compare} {b}")

Output

1 less 5
5 greater 3
10 equal 10
44 less 55
4 greater 3

Upvotes: 1

Jules
Jules

Reputation: 385

Assuming both lists are equal length you can use a while loop

i = 0
while i < len(nums1):
    if num1[i] == nums2[i]:
        # do something when equal
    i = i + 1

Upvotes: 0

Related Questions