Introduction to Python – Data Structures (Lists)
- Data structures are used to store a collection of related data. There are four built-in data structures in Python – list, tuple, dictionary and set.
- ***NOTE: It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.***
Lists as Stacks
- The last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.
Lists as Queues
- The first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
- To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends.
- Notice the queues only can pop from left to right.
- <+Make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
- Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects.
- A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal.
- Notice that the order of the for and in statements are in the same order in both of the examples.
Methods for List Objects
- append – Used to add an object to the end of a list.
***Notice append will only take one argument at a time.***
- extend – Extends a list by adding all items from the iterable.
***Notice the difference between append and extend.***
- insert – Inserts the object into a list at a given index. (0 = beginning of the list)
- remove – Removes an object from a list. You must specify the object to be removed. If it is a string you must specify the sting.
Clear – Clears all objects out of a list.
- index – locate and search for an object within the list starting at a given index.