What are the ways to traverse a list in Python?

Release: 2019-07-08 09:03:26
Original
9089 people have browsed it

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)
Copy after login
lists = ["m1", 1900, "m2", 2000]
for item in lists:
item = 0;
print(lists)
Copy after login

Run result:


['m1', 1900, 'm2', 2000]
Copy after login

2. While loop traversal:


lists = ["m1", 1900, "m2", 2000]
count = 0
while count < len(lists):
print(lists[count])
   count = count + 1
Copy after login

3. Index traversal:


for index in range(len(lists)):
   print(lists[index])
Copy after login

4. Use iter()


for val in iter(lists):
    print(val)
Copy after login

5. enumerate traversal method

for i, val in enumerate(lists):
    print(i, val)
Copy after login

Running results:

0 m1
1 1900
2 m2
3 2000
Copy after login

When traversing elements starting from non-0 subscripts, you can use the following method

for i, el in enumerate(lists, 1):
    print(i, el)
Copy after login

Running results:

1 m1
2 1900
3 m2
4 2000
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!