-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path06_datastructuresExample.py
More file actions
executable file
·94 lines (69 loc) · 1.77 KB
/
06_datastructuresExample.py
File metadata and controls
executable file
·94 lines (69 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python3
"""
Examples using lists, tuples and dictionaries (dict)
https://docs.python.org/3/tutorial/datastructures.html
Jens Dede, 2019, jd@comnets.uni-bremen.de
"""
# Lists
###
print(5*"#", "Lists")
l = [1,2,3] # List with three values
# Append some items (numbers)
l.append(12)
l.append(13)
l.append(14)
l.append(15)
# Print complete list
print("Complete list", l)
# Print parts of the list
print("First entry:", l[0])
print("Last entry:", l[-1])
print("Only till the 2nd entry:", l[:2])
print("Only the last 2 entries:", l[-2:])
# Change a list item
l[1] = 123
# Lists can be sorted
l.sort()
print("Changed list:", l)
# Iterate over the list
for i in l:
print("List item", i)
# Tuples
###
# \n creates a new line
print("\n\n",5*"#", "Tuples")
# Create a tuple
t = (1,2,3,4,5)
# Accessing tuple items
print(t, t[0])
# Iterate over a tuple
for i in t:
print("Tuple item", i)
# Tuples cannot be changed after assigning them!
# Advantage: They are faster than lists
# Dictionaries (dict) (key-value storage)
###
# \n creates a new line
print("\n\n",5*"#", "Dictionaries (dict)")
data = {} # Empty dict
data["name"] = "My Name" # Assign value "My Name" using key "name" to dict data
data["address"] = "My Address"
# Access dict item using key
print('data["name"]:', data["name"])
# Print complete dict
print("data:", data)
# Iterate over dict
for key in data:
print("key:", key)
print("data:", data[key])
# Init a dictionary with values
myDict = {
"valueA": "Hallo",
"valueB": [1,2,3,4]
}
print(myDict)
print(myDict["valueA"])
# What to try out
#################
# - You can combine the datatypes. Create a list of dictionaries containing the
# first name and the last name. Access the elements and change something.