As in any programming language, there are also some pitfalls in Python that even experienced programmers have to deal with sometimes. You can deal with them too if you know them as a potential source of danger.
THE VARIABLE MEMORY MODEL OF PYTHON
In chapter 2.6the concept of variables was introduced by a visual representation, the so-called box metaphor. A variable declaration, for instance a = 100, was considered to be a reservation of space in computer memory to hold the number 100, simular to creating a drawer or a box and putting the number 100 inside. Similar to mathematics, the letter a stands for a variable identifier (name or place holder). However this simple idea is not entirely correct in Python, since all data, including numbers, are regarded as objects and an object does not only have a value, but also define "behavior" using functions (or methods). As an example number objects "knows" how to add values.
Sometimes we say that 2 is the address of the object, in Python called id (identifier).
In Python, by assigning a value to a variable, you create a name a that points to (or refers) to an int object, that is stored at memory address 0x2. Therefore a is also called an "alias" (or on other programming languages a reference or pointer). This situation can be represented symbolically:
The difference to the box metaphor becomes clearly visible in the following assignment:
Actually this statement does not create a second box and put the number 100 inside, but simply creates a second alias b that refers to the same object that holds 100, as shown here:
The situation looks like this:
The awareness of this concept becomes most important when the data is not a simply number, but a structured data type (like a list) as shown in the following example.
As you suspect correctly the situation can be represented as follows
If you modify now the list using the alias b
Therefore you also changed the list referenced by a (it is the same)!
This mutual dependency of the two variables a and b causes many subtle programming errors. But there is no danger if you define a completely new variable b because now you create a new object and the two objects a and b are completely independent.
Now if you modify the list b:
the list a remains unchanged as you can easily check:
For simple data types like numbers, this mutual dependency does not harm because if you modify a number, a new number is automatically created. Indeed after the new assignment of b, a new object is created in memory. The alias that referred to value 100 after the second line b = a now refers to a new object 200 after the third line.
The following example demonstrates once again that the assignment of list variable is dangerous since the content of the list is not copied into the new list.
If you want to create an independent copy (also called a clone) for mutable data types, for example of lists, you have to either copy the elements explicitly into a new variable with your own code, or you can use the function deepcopy() from the module copy:
As a consequence we formulate the following rule:
Rule 1 is often ignored in the context of parameter passing. Each time you pass a function a mutable data type, the function can change the values without any problems.
After calling show(), the values of the passed parameters changed! Just like in medicine, it is usually an unexpected and unwanted adverse effect or side effect.
PACKING & UMPACKING
At first glance, tuples do not seem to differ significantly from lists. As a matter of fact, tuples are basically immutable lists and thus all list operations that do not change the list, are also applicable to tuples. However, there are special notations techniques with tuples using commas.
Round parentheses can be omitted in the generation of tuples:
In this case, the comma is used as a syntax character to separate the elements from each other. This is called automatic packing. You can smartly make use of this to return multiple function values as tuples:
You can also use the comma operator on the left side when defining variables in case a tuple is placed after the equal sign. In this case, one speaks of automatic unpacking:
Packing is convenient for defining multiple variables simultaneously:
In the following, the three numbers are packed on the right side and unpacked again on the left side:
By the way, unpacking also works with lists:
Using this syntax, two numbers can be permuted in an elegant way without requiring an auxiliary variable:
MUTUAL AND IMMUTUAL DATA TYPES
To improve data security by undesirable side effects, Python relies on the concept of alterable (mutable) and non-alterable (immutable) data types. The latter include the numbers, strings (str), and byte tuple. For example changing a letter in a string causes an error message:
To modify s, you need to redefine the whole string:
Now a new string object is created and the reference to the old is lost (the memory space is freed by an internal garbage colllector).
TWO-DIMENSIONAL LISTS, MATRICES
Matrices are constructed as arrays in many programming languages. The rows of the matrix are arrays and the matrix itself is an array of these row arrays. It is straightforward to use lists instead of arrays in Python. However, you have to pay close attention since lists do not behave like elementary data types (immutable), but rather like reference types. You already get into a known pitfall during the creation of the matrix. Without knowing it, you generate a 3x3 matrix with zeros in the Python console.
You now change the last value of the first row using an allocation. You are probably surprised to notice that all other rows change too.
What happened there? Thinking about it a little will start you off. Generating A could have also been done in two steps:
First, a list z is generated with three zeros. Then a list A is made with three times the same line reference. All refer to the same list! If you change one of them, the others will also be affected.
To get around the pitfalls, you can use list comprehension. As you can test out, the matrix now behaves properly: