In Python How can I declare a Dynamic Array

Srinath picture Srinath · May 26, 2010 · Viewed 181.8k times · Source

I want to declare an Array and all items present in the ListBox Should Be deleted irrespective of the Group name present in the ListBox. can any body help me coding in Python. I am using WINXP OS & Python 2.6.

Answer

Michael Aaron Safyan picture Michael Aaron Safyan · May 26, 2010

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