Home>Article>Backend Development> What are the ways to traverse a list in Python?
There are several ways to traverse a list in Python:
##1. For loop traversallists = ["m1", 1900, "m2", 2000] for item in lists: print(item)
lists = ["m1", 1900, "m2", 2000] for item in lists: item = 0; print(lists)Run result:
['m1', 1900, 'm2', 2000]2. While loop traversal:
lists = ["m1", 1900, "m2", 2000] count = 0 while count < len(lists): print(lists[count]) count = count + 13. Index traversal:
for index in range(len(lists)): print(lists[index])4. Use iter()
for val in iter(lists): print(val)5. enumerate traversal method
for i, val in enumerate(lists): print(i, val)Running results:
0 m1 1 1900 2 m2 3 2000When traversing elements starting from non-0 subscripts, you can use the following method
for i, el in enumerate(lists, 1): print(i, el)Running results:
1 m1 2 1900 3 m2 4 2000For more Python-related technical articles, please visit the
Python Tutorialcolumn to learn!
The above is the detailed content of What are the ways to traverse a list in Python?. For more information, please follow other related articles on the PHP Chinese website!