# How do I compare the variables when using zip in a for loop?

#1

## Question

How do I compare the variables when using zip in a for loop?

`a` and `b` are elements from the resulting combined list. If we have two lists, `list_a` and `list_b`, then `zip()` combines them to the shortest length of the two, like this:

``````list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
# RESULT: (3,2), (9,4), (17,8), (15,10), (19,30)
``````

The resulting pairs of elements are stored in `a` and `b` respectively. So the first time our loop runs, `a` will be `3` and `b` will be `2`. Comparing these two variables is done as a comparison between two numbers, since they are not lists.
`if a > b:`, for example.

FAQ: Learn Python- Loops - Multiple lists
#2

How do you print the larger of the two lists?

#3

define larger? The list with most elements? Or do you want to compare values at the same index position in the different lists? So compare 3 with 2 (index 1), compare 9 with 4 (index 2) and so on?

#4

Yes, I meant the latter.

#5

just use a for loop with zip, and inside the loop compare the values.

#6

2 posts were split to a new topic: Problem creating my own

#8

I’ve used a for loop, the code works but it prints it 4 times, i think
my code is a bit off, can someone help me out:

for a, b in zip(list_a, list_b):
if a > b:
print list_a

#9

Because you’re printing the whole list `list_a` every time.
You only want to print `a` if `a` is bigger, and `b` if `b` is bigger

#10

how do i print the larger(list with the most elements) list of the two lists

#11

you could compare the length of the lists?

#12

can we do it without using len(list) function?

#13

could we? Yea, very likely. But the better question: should you?

#14

We should note that when two lists are not the same length, the zipped list length will be that of the shorter of the two.

``````zip ([1,2,3,4,5],['a','b','c'])
``````

becomes,

``````[(1, 'a'), (2, 'b'), (3, 'c')]
``````

and we lose the last two values of the numbers list.