Home  >  Article  >  Backend Development  >  What are the ways to traverse a list in Python?

What are the ways to traverse a list in Python?

尚
Original
2019-06-26 18:06:089045browse

What are the ways to traverse a list in Python?

There are several ways to traverse a list in Python:

##1. For loop traversal

lists = ["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 + 1

3. 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 2000

When 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 2000

For more Python-related technical articles, please visit the

Python Tutorial column 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn