Python for-loop without index and item

天涯浪子 提交于 2021-01-18 04:55:26

问题


Is it possible in python to have a for-loop without index and item? I have something like the following:

list_1 = []
for i in range(5):
    list_1.append(3)

The code above works fine, but is not nice according to the pep8 coding guidelines. It says: "Unused variable 'i'".

Is there a way to make a for-loop (no while-loop) without having neither the index nor the item? Or should I ignore the coding guidelines?


回答1:


You can replace i with _ to make it an 'invisible' variable.

See related: What is the purpose of the single underscore "_" variable in Python?.




回答2:


While @toine is completly right about using _, you could also refine this by means of a list comprehension:

list_1 = [3 for _ in range(5)]

This avoids the ITM ("initialize, than modify") anti-pattern.



来源:https://stackoverflow.com/questions/24928585/python-for-loop-without-index-and-item

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