In the following article, we will learn aboutiterationin python. Understand what iteration means and what role it can play in python programming.
What is iteration in python
If a list or tuple is given, we cantraverse the list or tuple through a for loop, this This kind oftraversalis callediteration(Iteration).
(In Python, iteration is done through for...in)
Python’s for loop is more abstract than C’s for loop because Python's for loop can be used not only on lists or tuples, but also on otheriterable objects.
(Objects that can be directly used in for loops are collectively called iterable objects (Iterable), such as list, tuple, dict, set, str, etc.)
list Although this data type has subscripts, many other data types do not have subscripts. However, as long as it ispython'siterable object, it can be iterated regardless of whether it has a subscript or not. , for example, dict can be iterated:
>>> d = {'a': 1, 'b': 2, 'c': 3} >>> for key in d:... print(key) ... a c b
>>> for ch in 'ABC': ... print(ch) ...ABC
>>> from collections import Iterable >>> isinstance('abc', Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False
>>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... print(x, y) ... 1 1 2 4 3 9
pythonknowledge, I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.
For more related knowledge, please visit thePython tutorialcolumn on the php Chinese website.
The above is the detailed content of What are iteration and iteration objects in python?. For more information, please follow other related articles on the PHP Chinese website!