Lists & Tuples
#
Basic OperationsInitialising a list: myList = [0] * 6
Accessing last element in a list: myList[-1]
Operation Name | Operator | Explanation | |
---|---|---|---|
indexing | [ ] | Access an element of a sequence | |
concatenation | + | Combine sequences together | |
repetition | * | Concatenate a repeated number of times | |
membership | in | Ask whether an item is in a sequence | |
length | len | Ask the number of items in the sequence | |
slicing | [ : ] | Extract a part of a sequence |
#
Other Operations Useful for Data StructuresNote: Some of the methods mutate the original list, whereas other return a modified new list
Operation Name | Operator | Explanation |
---|---|---|
append | alist.append(item) | Adds a new item to the end of a list |
insert | alist.insert(i,item) | Inserts an item at the ith position in a list |
pop | alist.pop() | Removes and returns the last item in a list |
pop | alist.pop(i) | Removes and returns the ith item in a list |
sort | alist.sort() | Modifies a list to be sorted |
reverse | alist.reverse() | Modifies a list to be in reverse order |
del | del alist[i] | Deletes the item in the ith position |
index | alist.index(item) | Returns the index of the first occurrence of item |
count | alist.count(item) | Returns the number of occurrences of item |
remove | alist.remove(item) | Removes the first occurrence of item |
#
Sorting Listskey
is the function that serves as the key for sorting.
Source: https://wiki.python.org/moin/HowTo/Sorting
When set to True
, reverse
sorts the list in a descending manner.
We can also use sorted
which performs stable sort.
Time complexity of the sort()
or sorted()
methods is O(nlog(n))
.
#
Using Lists as Stacks (LIFO)To add an item to the top of the stack, use
append()
. To retrieve an item from the top of the stack, usepop()
without an explicit index.- Python 3 Documentation
#
Using Lists as Queues (FIFO)We can use collections.deque
to have fast appends, and pops from both ends.
#
Iterating Lists#
Reversing a List#
Time Complexity of OperationsOperation | Big-O Efficiency |
---|---|
index [] | O(1) |
index assignment | O(1) |
append | O(1) |
pop() | O(1) |
pop(i) | O(n) |
insert(i,item) | O(n) |
del operator | O(n) |
iteration | O(n) |
contains (in) | O(n) |
get slice [x:y] | O(k) |
del slice | O(n) |
set slice | O(n+k) |
reverse | O(n) |
concatenate | O(k) |
sort | O(n log n) |
multiply | O(nk) |
#
List ComprehensionList comprehension allows us to create lists/sets/tuples/vectors easily.
Example:
Reference: http://www.secnetix.de/olli/Python/list_comprehensions.hawk
#
Creating a 2D Array#
TuplesTuples are similar to lists, but tuples are immutable.
Example declaration: myTuple = (4.5, True)
.
Other operations are similar to lists.