0

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

  • using a "for" loop
  • using a star operator in the print() method

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)
Marios
  • 3
  • 2

1 Answers1

4

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))

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
  • Thank you, it works well now. Just one more question on that: without turning the iterator into a list, I also tried to print it (e.g. print(result)) and I got as an output the following: . Since I just started with Python, I was wondering why, if the iterator is exhausted, doesn't it print just a blank instead. – Marios Nov 11 '20 at 14:47
  • That's the memory address that is printed, it's roughly equivalent to `hex(id(result))`. You will likely never need it though – Chris_Rands Nov 11 '20 at 17:50
  • I understand. Thank you! – Marios Nov 11 '20 at 18:20