Marios
Marios

Reputation: 3

Printing a tuple in Python using both "for" loop and unpacking with star operator (*)

I am trying to print the items of the "result" tuple in the following code in 2 different ways:

In the output, the string "reference point" is supposed to separate the results of the two ways.

animals = {"dog", "cat", "pig"}
numbers = (1, 2, 3)
column = ['a', 'b', 'c']
result = zip(animals, column, numbers)

#first way of printing the items in the result tuple
for item in result:
    print(item)

print('\nreference point\n')

#second way of printing the items in the result tuple
print(*result, sep="\n")

However, the code outputs only the first result (before the "reference point") regardless which way this is (either the "for" loop or the star operator), as shown below:

('dog', 'a', 1)
('pig', 'b', 2)
('cat', 'c', 3)

reference point

Does anyone know why the items of the "result" tuple are printed only once and how this can be fixed? I am looking for an output like the following:

('dog', 'a', 1)
('pig', 'b', 2)
('cat', 'c', 3)

reference point

('dog', 'a', 1)
('pig', 'b', 2)
('cat', 'c', 3)

Upvotes: 0

Views: 383

Answers (1)

Chris_Rands
Chris_Rands

Reputation: 41168

The iterator constructed by zip is exhausted at the first iteration, you need to re-build it or make it a list like result = list(zip(animals, column, numbers))

Upvotes: 4

Related Questions