What is the purpose of the single underscore “_” variable in Python?

后端 未结 5 1633
后悔当初
后悔当初 2020-11-21 04:04

What is the meaning of _ after for in this code?

if tbh.bag:
   n = 0
   for _ in tbh.bag.atom_set():
      n += 1
5条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 04:49

    Underscore _ is considered as "I don't Care" or "Throwaway" variable in Python

    • The python interpreter stores the last expression value to the special variable called _.

      >>> 10 
      10
      
      >>> _ 
      10
      
      >>> _ * 3 
      30
      
    • The underscore _ is also used for ignoring the specific values. If you don’t need the specific values or the values are not used, just assign the values to underscore.

      Ignore a value when unpacking

      x, _, y = (1, 2, 3)
      
      >>> x
      1
      
      >>> y 
      3
      

      Ignore the index

      for _ in range(10):     
          do_something()
      

提交回复
热议问题