Lists
Changing Lists
This chapter of our tutorial deals with further aspects of lists. You will learn how to append and insert objects to
lists and you will also learn how to delete and remove elements by using 'remove' and 'pop'
A list can be seen as a stack. A stack in computer science is a data structure, which has at least two operations:
one which can be used to put or push data on the stack and another one to take away the most upper element of the
stack.
The way of working can be imagined with a stack of plates. If you need a plate you will usually take the most upper one.
The used plates will be put back on the top of the stack after cleaning.
If a programming language supports a stack like data structure, it will also supply at least two operations:
- push
This method is used to put a new object on the stack. Depending on the point of view, we say that we "push" the object on top or attach it to the right side. Python doesn't offer - contrary to other programming languages - no method with the name "push", but the method "append" has the same functionality. - pop
This method returns the most upper element of the stack. The object will be removed from the stack as well. - peek
Some programming languages provide another method, which can be used to view what is on the top of the stack without removing this element. The Python list class doesn't possess such a method, because it is not needed. A peek can be simulated by accessing the element with the index -1:>>> lst = ["easy", "simple", "cheap", "free"] >>> lst[-1] 'free' >>>