Home >Backend Development >Python Tutorial >python iteration
In python, we can iterate over list, tuple, dict or other iterable objects to traverse and extract each element.
How to determine whether an object is an iterable object
To determine whether an object is an iterable object, you can use isinstance to determine whether it is an Iterable type of the collections module.
For example:
from collections import Iterable isinstance('hello world',Iterable) # True isinstance([1,2,3,4],Iterable) #True isinstance(231,Iterable) #False
List tuple string When looping
fruits = ['apple','banana','peal','water melon'] for fruit in fruits: print fruit
while iterating, I want to get the subscript while getting the value. What should I do?
We can use the built-in enumerate() function in python to assemble list, tuple, string, etc. into an indexed enumerate object.
for index,fruit in enumerate(fruits): print index,fruit
Dict iteration
Dict dictionary itself has key and value.
When using for...in... iteration, the default is key iteration.
Dict 迭代 Dict字典本身带有key和value。 利用for...in...迭代的时候,默认是key迭代。
The output result will be:
banana apple peal
So what if it is a value iteration?
We can use the itervalues function of the dictionary itself.
for value in d.itervalues(): print value
We want both key and value during iteration, what should we do?
for key,value in d.iteritems(): print key,value