python中的for循环中的in的作用,表达式中的Python'in'关键字与for循环中的Python

I understand what the in operator does in this code:

some_list = [1, 2, 3, 4, 5]

print(2 in some_list)

I also do understand that i will take on each value of the list in this code:

for i in [1, 2, 3, 4, 5]:

print(i)

I am curious if the in operator used in the for loop is the same as the in operator used in the first code.

解决方案

They are the same concept but not the same operators.

In the print(2 in some_list) example, in is an operator that handles several different situations. The Python docs for the in operator give the details, which I paraphrase as follows: x in y calls y.__contains__(x) if y has a __contains__ member function. Otherwise, x in y tries iterating through y.__iter__() to find x, or calls y.__getitem__(x) if __iter__ doesn't exist. The complexity is to provide consistent membership testing for older code as well as newer code — __contains__ is what you want if you're implementing your own classes.

In the for loop, in is just a marker that separates the loop-index variable from whatever you're looping over. The Python docs for the for loop discuss the semantics, which I paraphrase as follows: whatever comes after in is evaluated at the beginning of a loop to provide an iterator. The loop body then runs for each element of the iterator (barring break or other control-flow changes). The for statement doesn't worry about __contains__ or __getitem__.

Edit @Kelvin makes a good point: you can change the behaviour of in with respect to your own new-style classes (class foo(object)):

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值