Better Python list Naming Other than “list”

江枫思渺然 提交于 2019-12-04 00:42:31

I like to name it with the plural of whatever's in it. So, for example, if I have a list of names, I call it names, and then I can write:

for name in names:

which I think looks pretty nice. But generally for your own sanity you should name your variables so that you can know what they are just from the name. This convention has the added benefit of being type-agnostic, just like Python itself, because names can be any iterable object such as a tuple, a dict, or your very own custom (iterable) object. You can use for name in names on any of those, and if you had a tuple called names_list that would just be weird.

(Added from a comment below:) There are a few situations where you don't have to do this. Using a canonical variable like i to index a short loop is OK because i is usually used that way. If your variable is used on more than one page worth of code, so that you can't see its entire lifetime at once, you should give it a sensible name.

goats

Variable names should refer what they are not just what type they are.

Python stands for readability. So basically you should name variables that promote readability. See PEP20.
You should only have a general rule of consistency and should break this consistency in the following situations:

  1. When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.

  2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style)

Also, use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
All this is taken from PEP 8

What about L?

Why not just use unsorted? I prefer to have names, which communicate ideas, not data types. There are special cases, where the type of a variable is important. But in most cases, it's obvious from the context - like in your case. Quick sort is obviously working on a list.

I use a naming convention based on descriptive name and type. (I think I learned this from a Jeff Atwood blog post but I can't find it.)

goats_list
for goat in goats_list : 
    goat.bleat()

cow_hash = {}

etc.

Anything more complicated (list_list_hash_list) I make a class.

Just use lst, or seq (for sequence)

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