Here’s how to program in Python – Part 2


script, laptop, programming, code

After our first introduction to Python, it is time to look at some more complex data structures: lists and dictionaries. We also dive into the structure of strings, so you can manipulate individual letters. Start your Python interpreter now!

In the previous lesson you learned to work with three data types in Python: int, float and str. Especially int and float are fairly simple data types. But in many programs you need types with more structure, we also call this data structures. In this part you will learn with two important data structures Python to work.

Lists

In many programs you do not work with one specific item, but with a whole series. A list (in Python list) is ideal for this. For example, you create a list of names:

>>> names = [‘kees’, ‘jan’, ‘pieter’, ‘jan’, ‘joris’, ‘rob’]
>>> len (names)

6

>>> empty_list = []

>>> len (empty_list)

0

The function len, which we know from the previous lesson to return the length of a string, also works on a list: then you get the number of elements in that list.

By the way, a list can contain elements of different types, such as a float, two strings and an int. But often a list only has elements of the same type.

Functions, parameters and arguments

Python divides a lot of functionality into functions: pieces of code that perform a specific task, such as len to get the length of a list or string. A function can have a parameter: a variable with which the function works and which gets as value the object that you pass to that function. We call that object the argument of the function. A function can also have multiple parameters (and therefore arguments). In part 6 you learn to define your own functions and this all becomes even more clear.

Elements in a list

Python also has a lot of possibilities to work with the elements in a list. This is how you easily request an element from the list at a specific position (also called ‘index’):

>>> names[2]
‘pieter’

Note that the position in a list starts counting from 0: the first element is names[0], the second names[1], the third names[2] and so on. You would then think that you should request the last element with:

>>> names[len(namen)-1]
‘rob’

That works, but Python also allows a negative position, which you start counting from the back of the list. The last element then has position -1:

>>> names[-1]
‘rob’
>>> names[-2]
‘Joris’

If you have paid attention, you will see that the string ‘Jan‘is twice in the above list. You can request that number of times with the function count:

>>> names.count (‘jan’)
2
>>> names.count (‘pieter’)
1
>>> names.count (‘koen’)
0

You can also request the position of an element in a list:

>>> names.index (‘jan’)
1
>>> names.index (‘pieter’)
2
>>> names.index (‘koen’)
Traceback (most recent call last):
File ““, line 1, in
ValueError: ‘koen’ is not in list

As you can see you get an error message (ValueError) if the requested element is not in the list. For an element that is multiple times in the list, the function returns index only the first position back. But you can also ask to search from a specific position:

>>> names.index (‘jan’, 2)
3

Change a list

If you have created a list, you can still change it. For example, in the simplest case, you change one element:

>>> names
[‘kees’, ‘jan’, ‘pieter’, ‘jan’, ‘joris’, ‘rob’]
>>> names[1] = ‘koen’
>>> names
[‘kees’, ‘koen’, ‘pieter’, ‘jan’, ‘joris’, ‘rob’]

You can also flip or sort a list:

>>> names.reverse ()
>>> names
[‘rob’, ‘joris’, ‘jan’, ‘pieter’, ‘koen’, ‘kees’]
>>> names.sort ()
>>> names
[‘jan’, ‘joris’, ‘kees’, ‘koen’, ‘pieter’, ‘rob’]

You can also add an element to the end of a list, or add it at a specific position between the other elements:

>>> names
[‘jan’, ‘joris’, ‘kees’, ‘koen’, ‘pieter’, ‘rob’]
>>> names.append (‘aniek’)
>>> names
[‘jan’, ‘joris’, ‘kees’, ‘koen’, ‘pieter’, ‘rob’, ‘aniek’]
>>> names.insert (0, ‘lies’)
>>> names
[‘lies’, ‘jan’, ‘joris’, ‘kees’, ‘koen’, ‘pieter’, ‘rob’, ‘aniek’]
>>> names.insert (4, ‘mireille’)
>>> names
[‘lies’, ‘jan’, ‘joris’, ‘kees’, ‘mireille’, ‘koen’, ‘pieter’, ‘rob’, ‘aniek’]

You can also delete existing elements. This is how you delete with the function remove (x) the first element whose value is x:

>>> names
[‘lies’, ‘jan’, ‘joris’, ‘kees’, ‘mireille’, ‘koen’, ‘pieter’, ‘rob’, ‘aniek’]
>>> names.remove (‘pieter’)
>>> names
[‘lies’, ‘jan’, ‘joris’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’, ‘aniek’]
>>> names.remove (‘pieter’)
Traceback (most recent call last):
File ““, line 1, in
ValueError: list.remove (x): x not in list

As you can see, you will get an error if you ask to delete an element that is not in the list.

You can also delete an element at a given position. You do that with the function doll:

>>> names
[‘lies’, ‘jan’, ‘joris’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’, ‘aniek’]
>>> names.pop (2)
‘Joris’
>>> names
[‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’, ‘aniek’]

If you’ve paid attention, you’ll see that feature doll not only removes an element, but also returns the removed element as value on the command line (‘Joris‘).

Cut into a list

Python has a powerful way to cut a list into pieces: ‘slicing’. Remember the notation [n] for the nth element? With [n:] you get the elements back from index n, with [:n] the elements up to index n (not included) and with [m:n] the elements of index m to n (not including the latter). A few examples make this clear:

>>> names = [‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]
>>> names[1:]
[‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]
>>> names[:4]
[‘lies’, ‘jan’, ‘kees’, ‘mireille’]
>>> names[1:4]
[‘jan’, ‘kees’, ‘mireille’]

Since Python starts counting from 0 and counts the element itself in the start position of a slice but not in the end position, the slicing notation is quite confusing. It therefore helps to consider these positions as the positions of the commas in the list, counting from 1. Everything in between the commas at those positions is then the requested slice. Take for example names[1:4]. Because names equals [‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob‘], we take everything between the first and the fourth comma, so from before ‘Jan‘until after’mireille‘, in other words [‘jan’, ‘kees’, ‘mireille‘].

Slicing is also a powerful way to change part of a list. This is how you easily replace the previous slice in the list with a different name:

>>> names
[‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]
>>> names[1:4] = [‘bas’]
>>> names
[‘lies’, ‘bas’, ‘koen’, ‘rob’]

More strings

In a string, just like in a list, you get access to the nth element with the notation [n]. So you get with ‘anic ‘[1] the second character of the string ‘anic‘, or the letter n. Slicing also works with a string: ‘aniek'[1:4] is equal to nie. But beware: unlike a list, you cannot change a string. The attempt ‘anic ‘[1:4] = ‘r’ gives an error.

Dictionary’s

In a list, each element has its position as an index, so that you can easily request the element at a specific position. Another data structure is the ‘dictionary’, which uses a key as an index for its elements, often a string or a number. Each key of the dictionary must be unique, so that you can easily request the value associated with a specific key.

An example shows how to work with a dictionary:

>>> scores = {‘lies’: 5, ‘bass’: 2, ‘kees’: 1, ‘aniek’: 3}
>>> scores[‘aniek’]
3
>>> scores[‘bert’]
Traceback (most recent call last):
File ““, line 1, in
KeyError: ‘bert’
>>> len (scores)
4

This way you can easily request the score of a person based on his or her name. You can also see here that you will receive an error message if you request an element with an index that does not exist in the dictionary.

You can change a dictionary just like a list. You can change the value for a specific key, but you can just as easily add a new element: just assign a value to a new key. For example:

>>> scores
{‘lies’: 5, ‘bass’: 2, ‘kees’: 1, ‘aniek’: 3}
>>> scores[‘lies’] + = 1
>>> scores
{‘lies’: 6, ‘bass’: 2, ‘kees’: 1, ‘aniek’: 3}
>>> scores[‘bert’] = 1
>>> scores
{‘lies’: 6, ‘bass’: 2, ‘kees’: 1, ‘aniek’: 3, ‘bert’: 1}

You can remove a key and its value from the dictionary with the special keyword del:

>>> scores
{‘lies’: 6, ‘bass’: 2, ‘kees’: 1, ‘aniek’: 3, ‘bert’: 1}
>>> del scores[‘kees’]
>>> scores
{‘lies’: 6, ‘bass’: 2, ‘aniek’: 3, ‘bert’: 1}

Resume

In this section, we took a long time to consider one of the most commonly used data structures in Python: the list. The knowledge you have gained about lists can be reused for many other data types in Python. For example, we showed how the notation for an index and for ‘slicing’ is the same for a string. Another important data type that you saw in this part is the dictionary, in which you do not use a position but a key as an index. In the next part, we’ll leave the Python interactive sessions and write our first programs.

Task 1

You have the following list of names:

>>> names = [‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’, ‘aniek’]

Split this list into its last element and the rest of the list.

Elaboration of assignment 1

>>> names
[‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’, ‘aniek’]
>>> last_person = names.pop ()
>>> names
[‘lies’, ‘jan’, ‘kees’, ‘mireille’, ‘koen’, ‘rob’]
>>> last_person
‘anic’

This is a common application of the function doll (), which not only removes the element on a specific index, but also returns the removed element. You probably solved this command with:

last_person = names.pop (-1)

But the -1 is not necessary: ​​without index returns the function doll the last element back.

Exercise 2

Extract all characters from a string except the first and the last.

Elaboration of assignment 2

>>> name = ‘aniek’
>>> name[1:-1]
‘nie’

Slicing works exactly like a list with a string. Moreover, we can also use a negative index in slicing: -1 then refers to the last element. Since Python starts counting from 0 and counts the character itself in the start position of a slice but not in the end position, the slice refers [1:-1] so to all characters in the string except the first and the last.

Cheat sheet

data structure: a data type that consists of elements that are related to each other.
dictionary: a data structure in which you request elements based on a unique key.

index (in a list): position of an element in a list, starting from 0.

index (in a dictionary): key of an element with which it can be retrieved from a dictionary.

list: a data structure in which you request elements based on their position.
slicing: cutting a list or string into pieces.

.

Recent Articles

Related Stories

Stay on op - Ge the daily news in your inbox