开发者

How can I remember which of list.append and list.extend is which in Python?

In Python, lists ha开发者_开发问答ve two methods for adding elements to the end: "append" and "extend". One of them adds a single element to the list, and the other adds every element from an iterable to the end of the list. Do you know which is which? Did you know without having to look it up? If so, could you please share your secret for remembering which is which?


At least for me their literal meaning itself is clear enough to make the distinction between them.

One of the dictionary definition for append : Add to the very end
One of the dictionary definition for extend : Stretch out over a distance, space, time, or scope; run or extend between two points or beyond a certain point


I don't have a mnemonic. "Extend" just sounds longer to me -- "extension cord" -- "extended break" -- "extensive research" -- all the words with similar roots have to do with making something much longer, or with being somehow very long.

Appendages, on the other hand, don't add much to that to which they are appended. American Heritage Dictionary:

Something added or attached to an entity of greater importance or size; an adjunct.

More concretely, perhaps you could think of an extension cord, which could easily be much longer than the cord it extends. When I was a kid we had a -- what do you call them -- "weed-whacker" is the only name I can think of. It had like a 3-foot cord. They assumed you'd attach it to one of those fifty-foot bright orange extensions.

Conversely, you probably wouldn't bother with a short extension cord -- a foot-long extension cord is pretty useless, especially when it comes to yard tools. And a call like this:

l = [1,2,3,4,5]
l.extend([6])

Equally useless.


Do you know which is which?

  • Extend: adds a list
  • Append: adds only element

Did you know without having to look it up? If so, could you please share your secret for remembering which is which?

Experience for the most part. To add a single Element, you don't use Extend. Basically, don't use E with E.


Append is for a single element at the end. Won't raise any exception if you add a list, because in python you can add almost all to a list.

Extend adds a list to a list, more like a concatenation. This one will raise an exception if you add a single element. I bet that you'll learn with it ;-)


Use a mantra:

  • You append to a list - another element.
  • You extend a list - with another.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜