Python Lists
In Python, a list is a dynamic array. You can create one like this:
lst = [] # Declares an empty list named lstOr 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 itemOr, 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 listNote, 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 itTaken from this nice Stackoverflow response.