Home > OS >  Python - Why does enumerate() cause a later zip() to only pull from the last item in list?
Python - Why does enumerate() cause a later zip() to only pull from the last item in list?

Time:01-05

Code:

boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
for i, boylist in enumerate(boylist):
    print(f'Index {i} is {boylist} in my list')
#boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
girllist = ['Emma', 'Clara', 'Susan', 'Jill', 'Lisa']
for boylist, girllist in zip(boylist, girllist):
    print(f'{boylist} and {girllist} form a nice couple')\

Output:

Index 0 is Jim in my list
Index 1 is James in my list
Index 2 is Jack in my list
Index 3 is John in my list
Index 4 is Jason in my list
J and Emma form a nice couple
a and Clara form a nice couple
s and Susan form a nice couple
o and Jill form a nice couple
n and Lisa form a nice couple

When I uncomment line 4 output is correct and each full name is printed. So my question is why does this happen? What does enumerate do to my list that causes this behavior? And how would I go about fixing this issue without redeclaring my original list?

I have tried playing around and printing out the outputs of both the enumerated and zipped lists but I don't understand what causes this. Was hoping to see that maybe the list index address was stuck at the final value but I was not able to find anything or reset this address.

CodePudding user response:

Because you used boylist as your iteration variable in the first for loop. So each iteration sets boylist to one of the elements of the original list. At the end of the loop, boylist contains the last boy name. Therefore, the second loop is iterating over the characters of Jason, not the names in the original boylist.

Don't reuse variables like this, use

boylist = ['Jim', 'James', 'Jack', 'John', 'Jason']
for i, boy in enumerate(boylist):
    print(f'Index {i} is {boy} in my list')

girllist = ['Emma', 'Clara', 'Susan', 'Jill', 'Lisa']
for boy, girl in zip(boylist, girllist):
    print(f'{boy} and {girl} form a nice couple')

CodePudding user response:

code

def merge(list1, list2):
    dict_ = {list1[i]: list2[i] for i in range(min(len(list1), len(list2)))}
    merged_list = list(dict_.items())
    return merged_list


boy_list = ['Jim', 'James', 'Jack', 'John', 'Jason']
girl_list = ['Emma', 'Clara', 'Susan', 'Jill', 'Lisa']

for boy, girl in merge(boy_list, girl_list):
    print(f'{boy} and {girl} form a nice couple')

result:

Jim and Emma form a nice couple
James and Clara form a nice couple
Jack and Susan form a nice couple
John and Jill form a nice couple
Jason and Lisa form a nice couple
  • Related