Home  >  Article  >  Backend Development  >  How to loop through all elements of a list in python?

How to loop through all elements of a list in python?

烟雨青岚
烟雨青岚Original
2020-06-28 17:12:1013729browse

Method: First create a list ("stus = ['Monkey King','Zhu Bajie','Spider Spirit']"), and then traverse the list through a for loop ("for i in stus:print(i )").

How to loop through all elements of a list in python?

Traverse the list: Output all elements

Traverse the list in sequence

Rendering:

How to loop through all elements of a list in python?

Code:

# 创建列表
stus = ['孙悟空','猪八戒','沙和尚','唐僧','白骨精','蜘蛛精']
# 依次遍历列表
print(stus[0])
print(stus[1])
print(stus[2])
print(stus[3])

Traverse the list through a while loop

Rendering:

How to loop through all elements of a list in python?

##Code:

# 创建列表
stus = ['孙悟空','猪八戒','沙和尚','唐僧','白骨精','蜘蛛精']
# 通过while循环遍历列表
i = 0
while i < len(stus):
    print(stus[i])
    i += 1

Traverse the list through a for loop The best traversal method

Rendering:


How to loop through all elements of a list in python?

Code:

# 创建列表
stus = [&#39;孙悟空&#39;,&#39;猪八戒&#39;,&#39;沙和尚&#39;,&#39;唐僧&#39;,&#39;白骨精&#39;,&#39;蜘蛛精&#39;]
# 通过for循环遍历列表 
for i in stus:
    print(i)

Recommended tutorial: "

python tutorial"

The above is the detailed content of How to loop through all elements of 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