(Pre-view Tip: The code in this article is run using PyCharm)
(Content is concise, reading time is only a few minutes)
0
1
What is a List
A list consists of a series of elements arranged in a specific order.
In the variable stage, we can assign any content to a variable, allowing the variable to specifically refer to a particular item. However, at this point, the variable can only point to one content. A list breaks this limitation, as it contains multiple elements, and the elements have a certain order.
team_member = ['bin','xiaohu','uzi']
print(team_member)
With the above code, we can print all the contents of the list. If we want to print an element at a specific position, we need to use the “access” syntax.
print(team_member[0])
This time the code has added [0], which represents accessing the element at index 0 in the list team_member.
It is important to note that the index positions of elements in a list start from 0, not 1.
In Python, to conveniently access the last element, a special syntax is designed:
By specifying the index as -1, we can access the last element.
0
2
Modifying Elements
Using “=”, we can define a list, and similarly, we can modify the value at a specific index in the list using “=”.
team_member = ['bin','xiaohu','uzi']
team_member[0] = 'shy'
print(team_member[0])
0
3
Adding Elements
After creating a new list, we often encounter the need to add content, which can generally be divided into two types: adding to the end and adding at any position. The former uses append(), while the latter uses insert().
team_member = ['bin','xiaohu','uzi']
team_member.append('ming')
print(team_member)
team_member.insert(1,"tian")
print(team_member)
0
4
Deleting Elements
When we want to delete an element from the list, we can use del() or pop().
del permanently removes the element from the list, while pop allows you to record the deleted element through assignment, enabling you to continue using it later.
The difference between the two lies in their different function syntax, for example:
team_member = ['bin','xiaohu','uzi']
del team_member[2]
print(team_member)
winner = team_member.pop(0)
print(team_member)
print(winner)
Additionally, sometimes we may not know the position of the element to delete, but we know its content; in this case, we can use remove() to delete the element.
Similar to pop, after using remove to delete an element, you can still use that element.
team_member = ['bin','xiaohu','uzi']
winner = team_member.remove("uzi")
print(team_member)
print(winner)

Conclusion

That’s all for today, congratulations on learning another knowledge point.
Please click the “Read” button below to let me know we are learning together!
Author | Hanko
Images | Internet (Infringement will be deleted)
Public Account | Python is easy as long as you have hands
Zhihu | Python is easy as long as you have hands
Your every like and read, I appreciate!
