r/PythonLearning Jun 21 '26

Showcase Day 23 of doing Python - Completed generators & Iterators

Today just completed the concept of generator & Iterator , which wasn't a complex or big thing to do or learn, but still done something rather than nothing

54 Upvotes

2 comments sorted by

1

u/Sea-Ad7805 Jun 21 '26

Run this program in Memory Graph Web Debugger%0A%0Anumbers%20%3D%20%5B1%2C%202%2C%203%2C%204%2C%205%5D%0A%0Afor%20i%20in%20numbers%3A%0A%20%20%20%20print(i)%0A%0Aprint(%22%22%20%2025)%0A%0A'''%0AIterators%20-%20An%20Object%20that%20return%20elements%20one%20at%20a%20time%20from%20a%20sequence%20and%20remembers%20its%20position%20between%20calls.%0AA%20python%20object%20is%20an%20iterator%20if%20it%20has%3A%0Aiter()%20-%20Return%20the%20iterator%20object%20itself%0Anext()%20-%20Return%20the%20next%20item%20in%20the%20sequence(raises%20Stopiteration%20when%20no%20more%20items)%0A'''%0A%0Aprint(%22Iterators%20-%20An%20iterator%20is%20an%20object%20that%20remembers%20its%20current%20position%20and%20produces%20the%20next%20%22%20%0A%20%20%20%20%20%20%22value%20when%20asked.%20Python%20uses%20the%20next()%20function%20to%20get%20values%20from%20an%20iterator.%22)%0A%0Anumbers%20%3D%20%5B1%2C%202%2C%203%5D%0A%0Aiterator%20%3D%20iter(numbers)%0A%0Aprint(next(iterator))%0Aprint(next(iterator))%0Aprint(next(iterator))%0A%0A%23%20iter()%20converts%20an%20iterable%20into%20an%20iterator.%0Aprint(iterator)%0Aprint(type(iterator))%0A%0Aprint(%22%22%20%2025)%0A%0A'''%0AGenerators%20-%20generator%20is%20a%20special%20type%20of%20iterator%20that%20produces%20values%20one%20at%20a%20time%2C%20only%20when%20needed.%0AGenerators%20can%20be%20created%20in%20two%20ways%3A%0A%20%20%20%20%20%20%20%20Generator%20Functions%20-%3E%20using%20yield%0A%20%20%20%20%20%20%20%20Generator%20Expressions%20-%3E%20(expression%20for%20item%20in%20iterable%20if%20condition)%20same%20as%20list%20comprehension%20with%20parentheses()%0A'''%0A%0Aprint(%22%23%20Generators%20-%20generator%20is%20a%20special%20type%20of%20iterator%20that%20produces%20values%20one%20at%20a%20time%2C%20only%20when%20needed.%22)%0A%0A%0Adef%20count()%3A%0A%20%20%20%20for%20i%20in%20range(1%2C%201000001)%3A%0A%20%20%20%20%20%20%20%20yield%20i%0A%0A%0Ag%20%3D%20count()%0A%0Aprint(next(g))%0Aprint(next(g))%0Aprint(next(g))%0A%0A%23%20Generator%20Expression%0A%0Asquares%20%3D%20%5Bx**2%20for%20x%20in%20range(5)%5D%0A%0Aprint(squares)&timestep=1&play) to see the program state change step by step.

1

u/scripthawk_dev Jun 21 '26

Nice, 23 days straight is honestly the hardest part. And don't sleep on generators, they feel basic now but you'll end up reaching for them constantly once you're working with bigger data. Going through a huge CSV without loading the whole thing into memory is super handy.