Home  >  Article  >  Backend Development  >  An article to help you understand the basics of Python: list introduction and loop traversal

An article to help you understand the basics of Python: list introduction and loop traversal

Go语言进阶学习
Go语言进阶学习forward
2023-07-25 15:36:581071browse

1. List introduction

Think about it:

Strings can be used to store a string of information, so think about it Think about it, how to store the names of all classmates? Is it feasible to define 100 variables, each variable storing a student's name? Is there a better way?

Answer: List.

1. The format of the list

namesList= ['xiaoWang','xiaoZhang','xiaoHua']

is more powerful than the C language array in that the elements in the list can are of different types.

testList= [1, 'a']

2. Print the list

Print each character of the list.

namesList = ['xiaoWang','xiaoZhang','xiaoHua']
print(namesList[0])
print(namesList[1])
print(namesList[2])

Result:

An article to help you understand the basics of Python: list introduction and loop traversal


##

二、列表的循环遍历

1. 使用for循环

前面打印出列表中的每个字符,为了更有效率的输出列表的每个数据,可以使用循环来完成。

demo:

namesList = ['xiaoWang','xiaoZhang','xiaoHua']
for name in namesList:
    print(name)

结果:

An article to help you understand the basics of Python: list introduction and loop traversal

2. 使用while循环

为了更有效率的输出列表的每个数据,可以使用循环来完成

demo:

namesList = ['xiaoWang','xiaoZhang','xiaoHua']


length = len(namesList)


i = 0


while i<length:
    print(namesList[i])
    i+=1

结果:

An article to help you understand the basics of Python: list introduction and loop traversal


3. Summary

This article explains the basics of lists in Python, introduces common list loop operations, and uses rich cases , to help everyone better understand the common basic operations of lists.

The above is the detailed content of An article to help you understand the basics of Python: list introduction and loop traversal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete