We don’t have arrays; we have Python lists. Lists are super dynamic because they allow you to store more than one “variable” inside of them. Lists have methods that allow you to manipulate the values inside them. There is actually quite a bit to show you here so let’s get to it.
The brackets are just an indication for the index number. Like most programming languages, Python’s index starting from 0. So, in this example 1 is the second number in the list. Of course, this is a list of numbers, but you could also do a list of strings, or even mix and match if you really wanted to (not the best idea though). Alright, now let’s see if we can print out the whole list.
I told you we would come back to see how awesome the for loop is. Basically, variable a is the actual element in the list. We are incrementing an implicit index. Don’t get too worried about it. Just remember we are cycling through the list.
Common List Methods
There are number of methods for lists, but we will at least cover how to add and delete items from them. All of the list methods can be found on Python’s documentation website. Methods follow the list name. In the statement listName.append(2), append() is the method.
- .append(value) – appends element to end of the list
- .count(‘x’) – counts the number of occurrences of ‘x’ in the list
- .index(‘x’) – returns the index of ‘x’ in the list
- .insert(‘y’,’x’) – inserts ‘x’ at location ‘y’
- .pop() – returns last element then removes it from the list
- .remove(‘x’) – finds and removes first ‘x’ from list
- .reverse() – reverses the elements in the list
- .sort() – sorts the list alphabetically in ascending order, or numerical in ascending order
Try playing around with a few of the methods to get a feel for lists. They are fairly straightforward, but they are very crucial to understanding how to harness the power of Python.