Lists
List is ordered mutable sequence of ANY objects.
This means that it is allowed to change it's elements after creation: adding new, changing/removing existing etc.
Ways to create a list:
[]
list()
[1, 2, 3, [10, 20], 5]
Main methods
🪄 Code:
📟 Output:
Actually beside magical methods (containing __) there are not so much methods left
Worth to note that most methods are not returning anything - they are just directly changing the list itself because it is mutable object.
List methods
Method(s) | Description |
---|---|
| Return int - length of the list |
| Reverse order of elements of the list in place |
| Sort elements of the list in place |
| Add new element |
| Append elements of iterable to the end of the list |
| Return and remove the last element from the list |
| Return and remove element by index |
Method(s) | Description |
---|---|
| Return (or assign) element by index |
| Return new list - slice from element by index |
| Return new list - slice with step |
| Remove element of index |
| Remove part (starting from index |
| Return True/False - is object |
| Return new list - a sum of merged lists |
Method(s) | Description |
---|---|
| Return number of object |
| Return first index of object |
Last two we saw in strings as well.
Examples
Lists are indexable, starting at 0
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Sorting
Sorting of the list with elements of different types in Python 3 is forbidden (yields an TypeError exception about unsupported
<
operation).
🪄 Code:
📟 Output:
But we can workaround this by specifying your own sorting function (as argument key
) which should return some values of the same type which Python will be sorting instead of real values.
🪄 Code:
📟 Output:
Appending, extending
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
By extending nested list Python will treat all nested as elements just as other types
🪄 Code:
📟 Output:
Removing
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Other examples
We saw very similar examples for strings - because strings are sequence too. That is the core idea (called ducktyping) in Python - the same behavior even if the types are different.
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
IndexError
exception is raised for non-existent index element
🪄 Code:
📟 Output:
List slices
Slices of list object are a bit different to the slices of strings due to the fact that lists are mutable. Because of these additional operations are available:
slice deletion
slice assignment
Firstly, let's check regular list slice obtaining:
Slice obtaining
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Slice deletion
By using del
operator on the slice it is possible to delete target part from the original list:
🪄 Code:
📟 Output:
Slice assignment
By assignining the slice to another iterable, the content of that iterable will be used to replace the target part of the original list:
🪄 Code:
📟 Output:
List comprehensions
Fast, simple and "Pythonic" way to create a list
Common applications are to 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
🪄 Code:
📟 Output:
It's absolutely the same as:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
The order of loops matters:
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
It's possible to create nested list and use conditions as well:
🪄 Code:
📟 Output:
is equivalent to:
🪄 Code:
📟 Output:
Some "real-world" example:
Deep/shallow copy
🔥
Variables in Python (name bindings) are just points to an object in memory. By assigning one variable to another we make them point to the same object which may lead to various problems.
Operator is
allows comparing by ids - shows is two variables pointing to the same object
🪄 Code:
📟 Output:
Shallow copy of lists
Create completely new copy of the list - by creating a new list and adding elements one by one from old one
🪄 Code:
📟 Output:
🪄 Code:
📟 Output:
Shallow copy problems
If list has mutable object deeper than on the very first nesting level - shallow copy will cause similar problems as before.
🪄 Code:
📟 Output:
Deep copy
There is a special standard module for copying - copy
🪄 Code:
📟 Output:
Self-referencing list
List is seqence-like object that contains pointers to other objects which are treated as it's elements. That's why it's possible to add list to itself as element!
🪄 Code:
📟 Output:
In this case when we del
ete it - Python garbage collector won't delete from memory - because the number of reference to this object is not null
Usual Python console:
🪄 Code >>> and 📟 Output:
You need to be aware of such cases.
Lists for heavy calculations
If you use list for complex math calculations - consider using numpy
.
They are a bit slower to create:
🪄 Code:
📟 Output:
But they are much faster (x5 in the following example) for a vector operations:
🪄 Code:
📟 Output:
## Complexity of operations
🔥
Time-complexity (aka "Big O" or "Big Oh") of various operations in current CPython.
Generally, 'n' is the number of elements currently in the container. 'k' is either the value of a parameter or the number of elements in the parameter.
Operation | Average Case | Amortized Worst Case |
---|---|---|
Copy | O(n) | O(n) |
Append | O(1) | O(1) |
Insert | O(n) | O(n) |
Get Item | O(1) | O(1) |
Set Item | O(1) | O(1) |
Delete Item | O(n) | O(n) |
Operation | Average Case | Amortized Worst Case |
---|---|---|
Iteration | O(n) | O(n) |
Get Slice | O(k) | O(k) |
Del Slice | O(n) | O(n) |
Set Slice | O(k+n) | O(k+n) |
Extend | O(k) | O(k) |
Sort | O(n log n) | O(n log n) |
Multiply | O(nk) | O(nk) |
x in s | O(n) | |
min(s), max(s) | O(n) | |
Get Length | O(1) | O(1) |
As we can see from Complexity of operations section, list
has fast (complexity is O(1)
) such methods as append
and pop
which work with right end of the structure. So this is a FILO structure - "stack". So, if we want to achieve maximum performance we should use list as stack (and not use insert(0, x)
and pop(0)
methods).
Last updated