0

Why first the first loop generates expected results, but the second, although is the same loop generates empty list?

y = ["I am ok", "We are there", "Contraction: I've I'm won't"]
y1 = [(word for word in text.split(" ")) for text in y]

print("First:\n")
for i in y1:
    print(list(i))


print("\nSecond:\n")
for i in y1:
    print(list(i))

Results:

First:
['I', 'am', 'ok']
['We', 'are', 'there']
['Contraction:', "I've", "I'm", "won't"]

Second:
[]
[]
[]
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • 3
    If you're planning to iterate twice, turn your generator expression into a list comprehension. – Aran-Fey Jun 01 '18 at 12:44
  • 1
    Use https://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension link for the detailed usage n differences of generator vs comprehension expressions – nandal Jun 01 '18 at 12:56
  • Thanks for the answers. I didn't know that generators are one pass only. Thanks to the answers now I know. Correction is very simple. Second line shoud be: y1 = [[word for word in text.split(" ")] for text in y] – Tomek Pa Jun 01 '18 at 13:18

0 Answers0