Home > Backend Development > Python Tutorial > 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

Release: 2023-07-25 15:36:58
forward
1108 people have browsed it

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']
Copy after login

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

testList= [1, 'a']
Copy after login

2. Print the list

Print each character of the list.

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

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)
Copy after login

结果:

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
Copy after login

结果:

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!

Related labels:
source:Go语言进阶学习
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