When is not a good time to use python generators?

前端 未结 9 925
不思量自难忘°
不思量自难忘° 2020-11-27 10:27

This is rather the inverse of What can you use Python generator functions for?: python generators, generator expressions, and the itertools module are some of m

9条回答
  •  孤街浪徒
    2020-11-27 10:52

    You should prefer list comprehensions if you need to keep the values around for something else later and the size of your set is not too large.

    For example: you are creating a list that you will loop over several times later in your program.

    To some extent you can think of generators as a replacement for iteration (loops) vs. list comprehensions as a type of data structure initialization. If you want to keep the data structure then use list comprehensions.

提交回复
热议问题