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.
Because you used
boylist
as your iteration variable in the firstfor
loop. So each iteration setsboylist
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 ofJason
, not the names in the originalboylist
.Don't reuse variables like this, use