Only index needed: enumerate or (x)range?

后端 未结 8 2157
长发绾君心
长发绾君心 2020-11-29 09:46

If I want to use only the index within a loop, should I better use the range/xrange function in combination with len()

a = [1,2,3]         


        
8条回答
  •  萌比男神i
    2020-11-29 10:49

    Using xrange with len is quite a common use case, so yes, you can use it if you only need to access values by index.

    But if you prefer to use enumerate for some reason, you can use underscore (_), it's just a frequently seen notation that show you won't use the variable in some meaningful way:

    for i, _ in enumerate(a):
        print i
    

    There's also a pitfall that may happen using underscore (_). It's also common to name 'translating' functions as _ in i18n libraries and systems, so beware to use it with gettext or some other library of such kind (thnks to @lazyr).

提交回复
热议问题