Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

yeah in python it would be [str(x) for x in lst]


In more modern (idiomatic) Python you would use a generator expression so:

strList = (str(x) for x in lst)


Hi yawaramin, there's nothing less modern or idiomatic about list versus generator comprehensions in python. You would use a generator if you want to limit maximum memory usage, and/or if you know that the iterable only needs to be consumed once.


I've seen the for x in lst syntax before, but where should I start to learn about generators?


For list comprehensions, it's the same syntax, but in ()s rather than []s. A generator will be lazily evaluated (so until something tries to get a value out, nothing is computed) and can only be iterated through once. That's pretty much the only differences in that case.

There's more complex generator stuff you can do (ie. using the ``yield`` syntax inside functions), but unfortunately I don't know a good resource for that off the top of my head :).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: