Understanding split generator | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson

Understanding split generator

Have completed the split generator coding challenge but i'm not entirely sure i understand the benefit or if I've done it correctly. txt = input() def words(string): word_list = string.split() for word in word_list: yield word print(list(words(txt))) Once i have split the string it is already put into a list of words so i could just run... Word_list = string.split() Print(word_list) Which would complete the challenge. I understand generators are useful for memory usage but in this imstance im creating the list before hand so would it now use the same amount of memory?

28th Aug 2022, 12:42 PM
1 Answer
+ 1
To get the efficiency of a generator, where you don't generate the whole list up front, you wouldn't want to use split(). You'd want to use something that parses the string one word at a time. The reason you might want to do that, which probably doesn't apply to this simple case, is that you might have logic that stops the parsing under certain conditions. Thereby saving the effort and space of generating the whole list. Does that make sense?
8th Sep 2022, 8:45 PM
Steve - avatar