Python “IN PLACE” functions

China☆狼群 提交于 2019-12-21 06:18:59

问题


What's the particular reason that some functions in Python operate "IN PLACE", like [].sort and [].reverse, while some others like [].append not?


回答1:


According to my Programming Python 4th edition:

By default, pop is equivalent to fetching, and then deleting, the last item at offset −1. With an argument, pop deletes and returns the item at that offset—list.pop(-1) is the same as list.pop(). For in-place change operations like append, insert, del, and pop, no new list is created in memory, so execution is quick (performance may further de- pend upon which end is the “top,” but this in turn depends on Python’s current list implementation, as well as measurement concepts we’ll explore later).

There is actually a whole section devoted to this, but this pretty much answers your question.




回答2:


"in-place" refers to a sorting algorithms use of only the memory needed to store the list of items plus some small constant. Append isn't a sorting algorithm and thus "in-place" is not meaningful, or at least wouldn't mean the same thing. You're confusing "in-place" in sorting and whether or not it returns a reference to a new object or a modified version of the same object.



来源:https://stackoverflow.com/questions/5317817/python-in-place-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!