Python for-loop without index and item

后端 未结 2 1680
余生分开走
余生分开走 2021-01-03 19:27

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)
         


        
相关标签:
2条回答
  • 2021-01-03 20:09

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

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

    0 讨论(0)
  • 2021-01-03 20:11

    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.

    0 讨论(0)
提交回复
热议问题