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?

Answer

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.