1 + 2
3
We’ll take a look here at some of the fundamental aspects of the Python syntax. Our aim is not to be exhaustive and replicate the whole python official documentation, but rather to get down the basics that will allow us to start writing simple programs and building from there as we go.
Also: It is fine not to remember everything after the first read, we rather want to get familiar with the language and some of the common idioms – just go with the flow :)
We have numbers:
As we see, adding two integers results in an integer. We can also represent non-integer numbers as floats:
Also notice:
Also, these three numbers evaluate to equal, as we can check using the equality operator:
If we add an int
to a float
, we get:
Python also has strings:
Strings are very powerful and have many “methods” associated with them that facilitates manipulating them. For example:
There are many more methods defined. Whenever you’re trying to do some operation over a string consider checking first if the method is already there. You can inspect the methods like so:
We can format strings using a handy language construct: f-strings
. f-strings
allow us to easily format our strings in a dynamical fashion, even executing code inside them. For example:
'I think this inner shouting string should be lower'
Notice that we alternated ” and ’.
We’ll see more examples of f-strings
later on, as they are a super handy tool adding a lot of expresivity to the language.
We can store and use variables:
For example, to format a string:
'name is Nik, the last name Mamba. Their age=23'
Or with this handy f-string substitution:
We need to be careful with the behaviour of variables depending on their type. We will get back to that in a few paragraphs after we talk about mutability.
We can store elements in different kinds of containers.
list
is the most common of them. We can store basically anything in them, including repetitions of the same element:
['hello', 1, 2.0, ['having fun', 123], ['having fun', 123]]
We can access the elements of the list via their indices (starting at 0)
We can take parts of that list, a so-called slice, by indicating a slice of indexes. The slice has the syntax (start
, stop
, [step
]), the step
is optional and can be negative. The slice is inclusive on the left and exclusive on the right:
[2, 3, 4, 5]
Importantly, we can modify a list:
You should think of lists as a sequence of references to other elements (objects). Here’s a practical example:
Since long
is simply holding a reference to short
, if we modify short
, we’ll see that change propagate to long
.
We can add elements to a list using the .append
method:
Removing elements is also possible:
Signature: result.remove(value, /) Docstring: Remove first occurrence of value. Raises ValueError if the value is not present. Type: builtin_function_or_method
Mutability
In Python some types can be modified (thus we say there are mutable), for example list
. Others can’t be modified after creating them, thus immutable, for example tuple
.
Explore the buil-int methods associated to list, there are handy ones, like .sort
Names and Variables can be a bit tricky in Python. If you are interested in some more details about the inner workings, I recommend this talk
Similar to list
but immutable, which gives them some performance advantages (that you rarely care about). In practice, rather than because of performance, you should prefer them over lists when care about the mutability (see example below).
Sometimes we are forced to use immutable data structures, for example as dictionary keys. That’s a perfect use case for tuples too:
And we can retrieve that value as per usual:
In a subsquent chapter we will cover a more useful variation of tuple
, the NamedTuple
.
Sets will guarantee at most 1 occurrence of each element, so it’s ideal to maintain a container with unique elements.
Sets don’t preserve insertion order!
Sets are also much faster for lookups than lists and tuples. Let’s look at an example:
CPU times: user 739 ms, sys: 158 µs, total: 739 ms
Wall time: 735 ms
False
CPU times: user 712 ms, sys: 0 ns, total: 712 ms
Wall time: 709 ms
False
A dictionary is a mapping from keys
to values
. They keys are unique. The values can be anything.
{'learning': 1, 'python': 2, 'is': 3, 'fun': 4}
We can access them:
{'python': [1, 2, 3], 'tennis': [4, 5, 6]}
{'first': {'one': 1, 'two': 2}, 'second': {'three': 3, 'four': 4}}
It’s important to keep in mind that dictionaries consist of items that are key-value pairs. That means we can build them from those paired items:
We often want to iterate through the elements of a dictionary:
We can combine two collections, for example two lists, with the zip
function. zip
interleaves elements and stops as soon as the shortest collection is consumed:
The inverse operation to zip
can be done by unpacking (with *
) the arguments like this:
In Python we can “unpack” sequences directly during assignment:
We can iterate and unpack the items of a dictionary on the fly:
We can modify a dictionary, by updating an item or items: