Printing zip format before a loop and after a loop

76 Views Asked by At
users=int(input("enter the number of users whose data you want to enter"))  
List1=[]  
List2=[]  
List3=[]  
username=[]  
copied_list=[] 
for i in range(1,users+1):   
    print(f"Enter first name of user{i}")  
    List1.append(input())  
    print(f"Enter last name of user{i}")  
    List2.append(input())  
    print(f"Enter birth year of user{i}")  
    List3.append(input())  
Full_Details=zip(List1,List2,List3)  
print("Before for loop")  
print(list(Full_Details))  
for i in Full_Details:  
        username.append(i[0][0]+i[1]+i[2][-2:]) 
print("After for loop")  
print(list(Full_Details))  

**If i try to print Full_details after converting to a tuple before the for loop it is printing the list accuretly but if i try to print it after for loop it prints empty list.What's the logic behind it . I am not able to post a image of the output yet But the result is like
enter the number of users whose data you want to enter2
Enter first name of user1
Harsh
Enter last name of user1
sangwan
Enter birth year of user1
2003
Enter first name of user2
Dev
Enter last name of user2
sharma
Enter birth year of user2
2004
Before for loop
[('Harsh', 'sangwan', '2003'), ('Dev', 'sharma', '2004')]
After for loop
[]
**

1

There are 1 best solutions below

0
On BEST ANSWER

This is because the zip object in Python is an iterator. An iterator is an object that remembers the position of traversal. When you use the list() function once to convert the zip object into a list, the iterator reaches the end. Calling the list() function again won't generate more elements, hence returning an empty list.

In your code, the line print(list(Full_Details)) has already completely traversed the zip object Full_Details once. Therefore, when you call print(list(Full_Details)) again, it returns an empty list.

If you want to use the elements generated by the zip object multiple times, you can immediately convert it into a list after creating the zip object, as shown in the code below:

Full_Details = list(zip(List1,List2,List3))

This way, Full_Details becomes a list, and you can traverse it multiple times, getting the same results each time.

users=int(input("enter the number of users whose data you want to enter: "))  

List1=[]  
List2=[]  
List3=[]  
username=[]  
copied_list=[] 

for i in range(1,users+1):   
    print(f"Enter first name of user{i}: ", end="")  
    List1.append(input())  
    print(f"Enter last name of user{i}: ", end="")  
    List2.append(input())  
    print(f"Enter birth year of user{i}: ", end="")  
    List3.append(input())  

# Full_Details=zip(List1,List2,List3)  
Full_Details = list(zip(List1,List2,List3))

print("Before for loop")    
print(Full_Details)

for i in Full_Details:  
    username.append(i[0][0]+i[1]+i[2][-2:]) 

print("After for loop")  
print(Full_Details)