Part 8: Compound type operations
Part 1: The Python programming language
In the types section, we went over the most common data types used in Python, but we didn’t really learn how to use the complicated ones. Now, we’ll see how to perform operations on string, lists, dictionaries and files, called compound types because they are all an array of something: in this case, characters, any elements, key-value pairs and bytes, respectively.
Common string operations
As a reminder, strings are a widespread variable type. They are defined between single or double quotes. A substring of a string is just one part of that string. For the string “abc”, possible substrings are, for example, “a” or “ab”. Note every string is also a substring of itself. Let’s assume we have a variable of type string named s
and another named p (for pattern). Here are some useful built-in methods that will surely save you some time.
s.count(p)
will count the number of occurrences ofp
ins
.s.find(p)
will return the index of the beginning of the first occurrence ofp
ins
.s.join(sequence)
concatenates a sequence usings
as a separator (use""
for no separator).s.split([delimiter])
splits a string at every delimiter and put the pieces into a list. Recall arguments within square brackets are optional. If no delimiter is provided, Python will use" "
(a whitespace character) by default.
Common list operations
You will be using lists all the time when coding. A list is the Python equivalent of an array, and in this language, they are created as you go, that is, they don’t always have a fixed size – as you add elements, Python will allocate memory for them so you don’t have to. Basic operations on lists include adding and deleting an element, but there are more. Let’s use a list l and an element e to illustrate this (remember lists can be composed of any type, including other lists!):
l.append(e)
addse
to the end ofl
l.remove(e)
removese
froml
.l.pop(e)
removese
froml
and returnse
(similar to stacks in other programming languages).l.count(e)
counts occurrences ofe
inl
.l.reverse()
reversesl
in place (use reversed(l
) to keep the old list and return a new one).l.sort()
sortsl
in place (use sorted(l
) to keep the old list and return a new one).
Common dictionary operations
Dictionaries are arrays of key-value pairs. They are used all over the world in one form or another, in many different programming languages. You might have heard of them in the form of hashmaps or just maps. They are similar to a database or a table, but with every row storing just two columns: a key and its corresponding value. Here are some of the functions you will need when using them (assume a dictionary d
has been defined):
- d.clear() Clears d (removes all key-value mappings).
d.get(k) Returns the corresponding
d.keys() Return keys in d
d.values() Return values in d
d.items() Return key-value pairs in d