Programming & Scripting Tutorials

Python: More List Methods



Because methods are so useful we are going to cover some more in this lesson!
Firstly lets create a list to use with all of the list methods:

List = ['Zero', 'One', 'Two', 'Three']


Index


The "index" method simply gives you the elements number, for example the following would output 2:

List.index('Two')

This outputs two as "Two" has been assigned the number 2.

Insert


The "Insert" method simply inserts an element just before the one you specify in the arugments, for example to add "OnePointFive" before two we could use:

List.insert(2, 'OnePointFive')

Our list is now: ['Zero', 'One', 'OnePointFive', 'Two', 'Three']

Pop


Pop is just the opposite of insert; it removes an element from the list. For example to remove "OnePointFive" we could run:

List.pop(2)

This works because "OnePointFive" has been assigned the number 2.
Our list is now back to: ['Zero', 'One', 'Two', 'Three']

Remove


Remove removes the first occurance of whatever argument you give it, for example to remove the first occurance of "Zero" we could run:

List.remove('Zero')


Reverse


This simply makes the list go backwards (it reverses the list). To change ['One', 'Two', 'Three'] to ['Three', 'Two', 'One'] we could run:

List.reverse()

Please note that reverse doesn't take any arguments.


This Python tutorial was written by


Back to Python

Advertisement: