In Python, a list
is a dynamic array. You can create one like this:
lst = [] # Declares an empty list named lst
Or you can fill it with items:
lst = [1,2,3]
You can add items using "append":
lst.append('a')
You can iterate over elements of the list using the for
loop:
for item in lst:
# Do something with item
Or, if you'd like to keep track of the current index:
for idx, item in enumerate(lst):
# idx is the current idx, while item is lst[idx]
To remove elements, you can use the del command or the remove function as in:
del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list
Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:
for item in lst[:]: # Notice the [:] which makes a slice
# Now we can modify lst, since we are iterating over a copy of it
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…