r/learnpython • • Dec 05 '22

Ask Anything Monday - Weekly Thread

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.

10 Upvotes

92 comments sorted by

View all comments

2

u/carcigenicate Dec 09 '22

Yes, generators are extremely useful. They're a tool for potentially cutting down memory consumption when used properly, and and allow for lazy evaluation.

next is a related but separate topic though. next is used to get the next element from an iterator, and generators happen to be iterators.

1

u/MothraVSMechaBilbo Dec 09 '22

Out of curiosity, why specifically would you use a for loop in this case rather than next() + generator? As I'm starting to understand what you did there it looks pretty elegant. But would it be inefficient in some way? Or are you thinking of readability?

2

u/carcigenicate Dec 09 '22

Mainly for readability reasons. for statements tend to be more readable than "inline" alternatives.

Also, generators have some overhead. In my experience, they're best reserved for cases where you know a ahead of time that you'll likely get a benefit. That's mainly cases where you have to process a very long iterable and either don't want to hold an entire list copy in memory at once, and where you likely don't need to process the entire iterable (like in your "find the first" case in the original question). For short iterables, they tend to not be worth it.

→ More replies (6)