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


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.


How do you print the larger of the two lists?

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?

Yes, I meant the latter.

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

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

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

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

1 Like

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

you could compare the length of the lists?

1 Like

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

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

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'])


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

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

1 Like

why would any one want to loose values of a list?

Why, indeed. One thinks less that someone would want to lose values, and more of the nature of the zip() function to map corresponding values together. The lost values are a consequence and if we are not sure that the lists are of the same length then we should not be using a function that expects them to be equal in length.

1 Like

Both the ways it is working , Python is a great language to learn