Programming with Python
Kühne Logistics University Hamburg - Fall 2024
def
followed by the function name, parameters and a colonLecture '4. Data in more than one dimension' is 90 minutes long!
tuple()
function or the ()
syntax+
operator to concatenate tuples*
operator to repeat a tuplecount(x)
: Returns the number of times x
appears in the tupleindex(x)
: Returns the index of the first occurrence of x
('Peter', 25, 'Hamburg')
Note
We can also create tuples by listing the elements separated by commas.
('Peter', 25, 'Hamburg')
>Question: How would you access the age from the tuple?
*
operator to assign the remaining elements to a variableName: Peter
Other info: [25, 'Hamburg']
Warning
The output is positional, so we have to be careful with the order of the variables.
list()
function or the []
syntax>Question: Any idea why lists support more methods?
count(x)
: Returns the number of times x
appears in the listappend(x)
: Adds an element x
to the end of the listinsert(i, x)
: Inserts an element x
at index i
remove(x)
: Removes the first occurrence of element x
index(x)
: Returns the index of the first occurrence of x
pop([i])
: Removes the element at index i
and returns itsort()
: Sorts the list in ascending orderreverse()
: Reverses the list>Task: Solve the following problem using lists:
Tip
You can use the methods and loops we learned so far to solve the problem.
set()
function or the {}
syntax+
and *
operations like lists and tuplesadd(x)
: Adds an element x
to the setremove(x)
: Removes an element x
from the setdiscard(x)
: Removes an element x
from the set if it is presentpop()
: Removes and returns an arbitrary element from the setupdate(other)
: Adds all elements from other
to the setunion(other)
: New set with elements from both setsintersection(other)
: New set with common elementsisdisjoint(other)
: True
if no elements in commonissubset(other)
: True
if subset of other
Tip
There are more methods for sets! If you are working intensively with sets, keep that in mind.
>Task: Solve the following problem using sets:
Tip
Notice, there is a small error in the given code that you have to fix.
dict()
function or the {}
syntaxNote
Note, how we can use the []
operator to access the value of a key?
Common operations and methods:
in
operation to check if a key is in the dictionary
for
loop to iterate over the dictionary
keys()
method to return a view of the dictionary’s keys
values()
method to return a view of the dictionary’s values
pop(key[, default])
to remove a key and return its value
>Task: Solve the following problem using dictionaries:
Tip
This impacts your code, the operations you can perform and the speed of your program. Thus, it makes sense to understand the differences and choose the right data type for the task.
Tip
You can convert between the data types using tuple()
, list()
, set()
and dict()
. Note, that this is not always possible, e.g. you cannot convert a list to a dictionary without specifying a key.
import timeit
# Number of elements in each data structure
n = 10000000
# Setup for each data structure, including the test function
setup_template = """
def test_membership(data_structure, element):
return element in data_structure
data = {data_structure}
"""
setups = {
'Tuple': setup_template.format(data_structure=f"tuple(range({n}))"),
'List': setup_template.format(data_structure=f"list(range({n}))"),
'Set': setup_template.format(data_structure=f"set(range({n}))"),
'Dictionary': setup_template.format(data_structure=f"{{i: i for i in range({n})}}")
}
# Measure time for each data structure
print(f"Time taken for a single membership test in {n} elements (in seconds):")
print("-" * 75)
for name, setup in setups.items():
stmt = f"test_membership(data, {n-1})" # Test membership of the last element
time_taken = timeit.timeit(stmt, setup=setup, number=1)
print(f"{name:<10}: {time_taken:.8f}")
print("-" * 75)
print("Note, that theses values are machine dependent and just for illustration!")
Time taken for a single membership test in 10000000 elements (in seconds):
---------------------------------------------------------------------------
Tuple : 0.05766171
List : 0.05379279
Set : 0.00000304
Dictionary: 0.00000408
---------------------------------------------------------------------------
Note, that theses values are machine dependent and just for illustration!
(x for x in iterable)
[x for x in iterable]
{x for x in iterable}
{x: y for x, y in iterable}
Tip
The iterable can be any object that can be iterated over, e.g. a list, tuple, set, dictionary, etc.
for
loop to iterate over an iterablecider
beer
bread
frozen_pizza
['Hello, World!', [1, 2, 3, 4, 5], (1, 2)]
(1, 2)
Tip
You can also nest lists within lists within lists, etc.
input()
function from the first lecture?print()
functionNote
Thus, we have already worked with I/O in Python!
open(file_name, mode)
to open a file"r"
(read), "w"
(write), "a"
(append)file.read()
file.write(content)
file.close()
File successfully written
>Question: Any ideas how to read the file?
Hello, World!
Tip
Close files with file.close()
to free up system resources and ensure data is properly saved.
with
statement to open a fileFile successfully written
>Task: Open the file hi_again.txt
and print its content using with
Note
And that’s it for todays lecture!
We now have covered the basics of tuples, sets, lists and dictionaries as well as some basic file handling. For now, just remember that advanced reading and writing is possible and that there are libraries that help with this.
Literature {.title}
Tip
Nothing new here, but these are still great books!
For more interesting literature to learn more about Python, take a look at the literature list of this course.
Lecture IV - Handling Data in more than one Dimension | Dr. Tobias Vlćek | Home