Traversing a list

The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:

                       

This works well if you only need to read the elements of the list. But if you want to write or update the elements, you need the indices. A common way to do that is to combine the functions range and len:

 

This loop traverses the list and updates each element. len returns the number of elements in the list. range returns a list of indices from 0 to n-1, where n is the length of the list. each time through the loop I gets the index of the next element. The assignment statement in the body uses I to read the old value of the element and to assign the new value.

A for loop over an empty list never executes the body:

 

Although a list can contain another list, the nested list still counts a single element. The length of this list is four:

 

 

from Thinking in Python

转载于:https://www.cnblogs.com/ryansunyu/p/3841087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值