sorted() using generator expressions rather than lists

前端 未结 8 1540
梦如初夏
梦如初夏 2020-11-30 05:31

After seeing the discussion here: Python - generate the time difference I got curious. I also initially thought that a generator is faster than a list, but when it comes to

8条回答
  •  有刺的猬
    2020-11-30 05:54

    There's a huge benefit. Because sorted doesn't affect the passed in sequence, it has to make a copy of it. If it's making a list from the generator expression, then only one list gets made. If a list comprehension is passed in, then first, that gets built and then sorted makes a copy of it to sort.

    This is reflected in the line

    newlist = PySequence_List(seq);
    

    quoted in Sven Marnach's answer. Essentially, this will unconditionally make a copy of whatever sequence is passed to it.

提交回复
热议问题