Python For Scientific Calculation VI

Willy Lim@
7 min readNov 7, 2022

Python Basics: Lists, Tuples & Dictionaries

When we were first learning about Python🐍 variables, we learnt that variables are containers for storing data values.

pokeball = "kitty"

output:

However, we might want to store a collection of values into a single container (under a variable name).

In Python 🐍, there are different ways of storing values into a variable.

  • Lists
  • Tuples
  • Dictionaries
  • Sets

Lists📃

A list is a collection of values which is ordered and changeable. It also allows duplicate members

this_is_a_list = ["apple", "mango", 123, 2.5]

The elements of a list are store between square brackets “[ ]”.

In Python🐍, everything is an object. A method is a function that “belongs to” an object. We have specific types of methods, depending on the type of object we have.

For the list, we can consider as methods, all the functions that belong to the object list.

Example of list methods

List Slicing 🔪

List slicing is a common practice and it is the most used technique for programmers to solve efficient problems.

Consider the following python🐍 list

participants = ['John', 'Leila', 'Maria', 'Dwayne', 'Anna']

In order to access a range of elements in a list, you need to slice🔪 the list. One way to do this is to use the simple slicing operator i.e. colon : ’

  • we want to access the elements of range index = 1 to index = 4
participants = [1:4]
  • 1 — first position of interest
  • 4 — one position above last position of interest

output:

Tuples

Tuples are also used to store multiple items in a single variable. It’s the default sequence type in Python 🐍

A tuple is a collection which is ordered and, unlike Lists, unchangeable or immutable.

We cannot append or delete elements from a tuple.

Tuples are written with round brackets “ ( )

numbers = (34, 43, 22)

There are only 2 methods associated with Tuples.

Tuples methods

Tuples assignment

One of the unique syntactic features of Python🐍 is the ability to have a tuple on the left side of an assignment statement. This allows us to assign more than one variable at a time when the left side is a sequence.

a tuple of variables, and a tuple of values

                          a, b, c = 1, 2, 3

a=1, b=2, and c=3 respectively

Another example📝

tup1 = ('John', 'Doe', 8574654, 95, 3.5)

we want to assign each one of these values oftup1 to a variable

(first_name, surname, student_id, maths_score, gpa) = tup1

the output of this Tuple Assignment is:

Dictionaries📖

Dictionaries are used to store data values in key-value pairs. A dict (Python🐍 short for dictionary) is a collection which is ordered, changeable and do not allow key duplicates.

We use curly braces ‘{ }’ to represent Dictionaries

This is a dict👇🏾

car = {
“brand”: “Ford”,
“electric”: False,
“year”: 1964,
“colors”: [“red”, “white”, “blue”]
}

Note

Both lists and tuples can be used as values for dicts but only tuples can be used as keys in a dict📖.

Some of the common methods used to manipulate dicts 📖 are:

Dicts methods

Let’s use Nikola Jokić stats to create a dictionary [ 2021–22 Kia NBA🏀MVP (Most Valuable Player) ]

NBA 21–22 MVP Nikola Jokić
nba_22_mvp = {
“name”: “Nikola Jokic”,
“nationality”: “Serbian”,
“age”:27,
“height_cm”: 210,
“weight_kg”: 128,
“position”:”center”
}

In case we want to extract some information from this dictionary, we can use the get() method.

We want to know the name of the MvP🏆

nba_22_mvp.get( ‘name’ )

the output:

Add, Update, and Delete Keys from a Dictionary📖

Add or Update Key

We can add a new key-value pair to NBA🏀MVP stats.

Let’s add a key: status with a value: active

nba_22_mvp['player_status'] = 'active'

We can also update a key-value pair.

let’s update his weight from 128 kg to 126 kg

nba_22_mvp['weight_kg'] = 126

Delete Keys from Dictionary

It is possible to remove a key and its corresponding value from a dictionary using del.

Let’s delete Nikola’s key age from our dict📖

   del nba_22_mvp['age']

We can see that the age is no longer available

Nested Lists — Tuples — Dicts

A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.

Lists📝, Tuples, and Dictionaries📖 can contain elements that are lists, tuples, or dictionaries themselves.

Let’s take the UEFA Champions League 🏆 as example #1

The UEFA Champions League (UCL) is UEFA’s elite club competition ⚽ with top clubs across the European continent playing for the right to be crowned European champions. The tournament, then called the European Cup, began in 1955/56 with 16 sides taking part.

UEFA 22–23 Group Stage

2022–23 Champions League group stage draw

Group A: Ajax, Liverpool, Napoli, Rangers
Group B: Porto, Atlético, Leverkusen, Club Brugge
Group C: Bayern, Barcelona, Inter, Viktoria Plzeň
Group D: Frankfurt, Tottenham, Sporting CP, Marseille
Group E: AC Milan, Chelsea, Salzburg, Dinamo
Group F: Real Madrid, Leipzig, Shakhtar, Celtic
Group G: Man. City, Sevilla, Dortmund, Copenhagen
Group H: Paris, Juventus, Benfica, Maccabi Haifa

let’s translate this to Python🐍

Each group is divided in 4 teams

A = ['Ajax', 'Liverpool', 'Napoli', 'Rangers ']
B = ['Porto', 'Atlético', 'Leverkusen', 'Club Brugge' ]
C = ['Bayern', 'Barcelona', 'Inter', 'Viktoria Plzeň' ]
D = ['Frankfurt', 'Tottenham', 'Sporting CP', 'Marseille']
E = ['AC Milan', 'Chelsea', 'Salzburg', 'Dinamo']
F = ['Real Madrid', 'Leipzig', 'Shakhtar', 'Celtic']
G = ['Man. City', 'Sevilla', 'Dortmund', 'Copenhagen ']
H = ['Paris', 'Juventus', 'Benfica', 'Maccabi Haifa']
champions_league_group_stage = [A, B, C, D, E, F, G, H]

How can we get access to Benfica football club?🤔 Benficais one of the teams in group H.

  • first, we have to get access to groupH in the champions_league_group_stage.

champions_league_group_stage[7]

output:

Benficais the 3rd element of list group H (index #2) 👇🏾

champions_league_group_stage[7][2]

output:

Example #2 — Creating Matrix

For Scientific Research🔬👨🏿‍🔬👩🏿‍🔬, creating a matrix is one of the most useful applications of nested lists. This is done by creating a nested list that only has other lists of equal length as elements.

matrix = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
]

Let’s try to multiply the first element of each row by 5.

knowing that the len() of the matrix is:

we can then proceed with our multiplication

print("matrix:")
for i in range(0, rows):
print(matrix[i][0]*5)

output:

From examples 1 & 2 we can conclude that:

  • The number of elements in the nested lists is equal to the number of rows of the champions_league_group_stage and matrix.
  • The length of the lists inside the nested list is equal to the number of columns.

Thus, each element of the nested list (matrix) will have two indices: the row and the column.

champions_league_group_stage[7][2] = 'Benfica'

matrix[i][0] = First element of each sublist.

Reference

💬

In our Dict📖 example, can you guess the output, in case we try to get() a key that does not exist? 🤔

What if have a list inside a list, how to access the last element of the second list?😕

Let me know the answers to these questions, or any suggestions that you might have in the comments section!😁

--

--