Python enumerate()

values = ["a", "b", "c"]

for index, value in enumerate(values):
	print(index, value)

# 0 a
# 1 b
# 2 c

When you use enumerate(), the function gives you back two loop variables:

  1. The index of the current iteration
  2. The value of the item at the current iteration

With enumerate(), you don’t need to remember to access the item from the iterable, and you don’t need to remember to advance the index at the end of the loop.

Python’s enumerate() has one additional argument that you can use to control the starting value of the count. By default, the starting value is 0 because Python sequence types are indexed starting with zero.

There are many times when you might not want the count from enumerate() to start at 0. For instance, you might want to print a natural counting number as an output for the user. In this case, you can use the start argument for enumerate() to change the starting count:

for index, value in enumerate(values, start=1):
	print(count, value)

# 1 a
# 2 b
# 3 c
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值