Skip to content
Snippets Groups Projects
Commit 5620e583 authored by Jöran Frey's avatar Jöran Frey
Browse files

Made some minor grammatical corrections till point when should we use lists...

Made some minor grammatical corrections till point when should we use lists and when should we use tuples
parent 19055948
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Extended Data Types # Extended Data Types
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Agenda # Agenda
* Lists (repetition) * Lists (repetition)
* Tuples * Tuples
* Sets * Sets
* Dictionaries * Dictionaries
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Introduction ## Introduction
* We already know lists * We already know lists
* Lists are only one of 4 built-in data types in Phython that store collections of data: * Lists are only one of 4 built-in data types in Phython that store collections of data:
* Lists * Lists
* Tuples * Tuples
* Sets * Sets
* Dictionaries * Dictionaries
* Collections are used to store multiple items in a single variable. * Collections are used to store multiple items in a single variable.
* Working with collections is something that makes Python extremly powerful * Working with collections is something that makes Python extremly powerful
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Recap of what we know about Lists ## Recap of what we know about Lists
1. Lists are created with square brackets ```[ ]``` 1. Lists are created with square brackets ```[ ]```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
list = [1,2,5,3] list = [1,2,5,3]
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
2. List items are ordered, changeable, and allow duplicate values 2. List items are ordered, changeable, and allow duplicate values
* Orders: Items have a defined order, and that order will not change unless we add or remove items * Orders: Items have a defined order, and that order will not change unless we add or remove items
* Changable: We can change, add, and remove items in a list after it has been created * Changeable: We can change, add, and remove items in a list after it has been created
3. We access list items by thier index (the position in the list, starting with 0) 3. We access list items by their index (the position in the list, starting at 0)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
list = [1,2,3,3,2] list = [1,2,3,3,2]
print(list[3]) print(list[3])
``` ```
%% Output %% Output
3 3
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Accessing List Items ## Accessing List Items
Besides accessing list items with ```[index]``` Python offers some additional options: Besides accessing list items with ```[index]``` Python offers some additional options:
1. Negative Indexing: ```[-1]``` refers to the last item, ```[-2]``` refers to the second last item etc. 1. Negative Indexing: ```[-1]``` refers to the last item, ```[-2]``` refers to the second last item etc.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
my_list = ['a','b','c','d'] my_list = ['a','b','c','d']
print(my_list[-1]) print(my_list[-1])
print(my_list[-2]) print(my_list[-2])
``` ```
%% Output %% Output
d d
c c
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
2. Instead of selecting a single item we can also select a subset of the list with the schema ```start-index:end-index``` 2. Instead of selecting a single item, we can also select a subset of the list with the schema ```start-index:end-index```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
my_list = ['a','b','c','d'] my_list = ['a','b','c','d']
print(my_list[1:3]) print(my_list[1:3])
``` ```
%% Output %% Output
['b', 'c'] ['b', 'c']
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## List Functions ## List Functions
We have already seen the most important list methods (functions). Here is a complete table: We have already seen the most important list methods (functions). Here is a complete table:
| Method | Description | | Method | Description |
| :-------- | :--------------------------------------------------------------------------- | | :-------- | :-------------------------------------------------------------------------- |
| append() | Adds an element at the end of the list | | append() | Adds an element at the end of the list |
| clear() | Removes all the elements from the list | | clear() | Removes all elements from the list |
| copy() | Returns a copy of the list | | copy() | Returns a copy of the list |
| count() | Returns the number of elements with the specified value | | count() | Returns the number of elements with the specified value |
| extend() | Add the elements of a list (or any iterable), to the end of the current list | | extend() | Adds an element of a list (or any iterable), to the end of the current list |
| index() | Returns the index of the first element with the specified value | | index() | Returns the index of the first element with the specified value |
| insert() | Adds an element at the specified position | | insert() | Adds an element at the specified position |
| pop() | Removes the element at the specified position | | pop() | Removes the element at the specified position |
| remove() | Removes the item with the specified value | | remove() | Removes the item with the specified value |
| reverse() | Reverses the order of the list | | reverse() | Reverses the order of the list |
| sort() | Sorts the list | | sort() | Sorts the list |
See https://www.w3schools.com/python/python_lists_methods.asp for more details. See [this page](https://www.w3schools.com/python/python_lists_methods.asp) for more details.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Tuples ## Tuples
* A tuple is a collection which is ordered and **unchangeable**. * A tuple is a collection that is ordered and **unchangeable**.
* Tuples are written with round brackets. * Tuples are written with round brackets.
* Tuples are orded and allow duplicate values. * Tuples are ordered and allow duplicate values.
* Items of tuples are accessed exactly the same way as lists with ```[]``` * tems in tuples are accessed in the same way as lists, using ```[]```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
my_tuple = ("mia", "mio", 1) my_tuple = ("mia", "mio", 1)
print(my_tuple[1]) print(my_tuple[1])
my_tuple[0] = "ciao" my_tuple[0] = "ciao"
``` ```
%% Output %% Output
mio mio
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
TypeError Traceback (most recent call last) TypeError Traceback (most recent call last)
Cell In[10], line 4 Cell In[10], line 4
1 my_tuple = ("mia", "mio", 1) 1 my_tuple = ("mia", "mio", 1)
2 print(my_tuple[1]) 2 print(my_tuple[1])
----> 4 my_tuple[0] = "ciao" ----> 4 my_tuple[0] = "ciao"
TypeError: 'tuple' object does not support item assignment TypeError: 'tuple' object does not support item assignment
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
* Tuples only know the methods ```count()```and ```index()``` * Tuples only know the methods ```count()```and ```index()```
* We use tuples to make sure, our data will not be changed anywhere in the code * We use tuples to make sure, our data will not be changed anywhere in the code
* Tuples are faster and more memory efficient than lists * Tuples are faster and more memory-efficient than lists
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## When should we use lists and when should we use tuples? ## When should we use lists and when should we use tuples?
* Use Lists, when you want to change data in your collection * Use Lists, when you want to change data in your collection
* Lists are more flexible and have more built-in methods, making them ideal for dynamic collections. * Lists are more flexible and have more built-in methods, making them ideal for dynamic collections.
* Use Tuples, when your data is immutable * Use Tuples, when your data is immutable
* We use tuples to make sure, our data will not be changed anywhere in the code. * We use tuples to make sure, our data will not be changed anywhere in the code.
* Tuples are faster and more memory efficient than lists (especially during iterations). * Tuples are faster and more memory efficient than lists (especially during iterations).
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Nested Lists and Tuples ## Nested Lists and Tuples
Since lists, tuples, and sets can contain any datatype we can also nest them: Since lists, tuples, and sets can contain any datatype we can also nest them:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
my_nested_list = [[1,2],[3,4]] # nested list (2D Array) my_nested_list = [[1,2],[3,4]] # nested list (2D Array)
my_nested_tuble = ((1,2),(3,4)) # nested tuble (2D Array) my_nested_tuble = ((1,2),(3,4)) # nested tuble (2D Array)
my_nested_3D_Matrix = ((1,2,5), my_nested_3D_Matrix = ((1,2,5),
(3,4,2), (3,4,2),
(3,3,3)) # Matrix (3,3,3)) # Matrix
print(my_nested_list[0][1]) print(my_nested_list[0][1])
print(my_nested_tuble[0][1]) print(my_nested_tuble[0][1])
print(my_nested_3D_Matrix[1][1]) print(my_nested_3D_Matrix[1][1])
``` ```
%% Output %% Output
2 2
2 2
4 4
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Sets ## Sets
* A set is a collection which is unordered, and unindexed and its itmes are unchangeable. * A set is a collection which is unordered, and unindexed and its itmes are unchangeable.
* Once a set is created, you cannot change its items, but you can add new items. * Once a set is created, you cannot change its items, but you can add new items.
* Dublicate items will be treated as one item * Duplicated items will be treated as one item
* Like lists and tuples, sets can contain multiple data types * Like lists and tuples, sets can contain multiple data types
* You cannot access items in a set by referring to an index or a key (since they have no order) * You cannot access items in a set by referring to an index or a key (since they have no order)
* Sets are written with curly brackets. * Sets are written with curly brackets.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
my_set = {1, 5, 3, 1} # last value will be ignored my_set = {1, 5, 3, 1} # last value will be ignored
my_set.add(1) # will be ignored my_set.add(1) # will be ignored
for x in my_set: for x in my_set:
print(x) print(x)
print(my_set[2]) print(my_set[2])
``` ```
%% Output %% Output
1 1
3 3
5 5
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
TypeError Traceback (most recent call last) TypeError Traceback (most recent call last)
Cell In[1], line 5 Cell In[1], line 5
3 for x in my_set: 3 for x in my_set:
4 print(x) 4 print(x)
----> 5 print(my_set[2]) ----> 5 print(my_set[2])
TypeError: 'set' object is not subscriptable TypeError: 'set' object is not subscriptable
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Example of using Sets ## Example of using Sets
* Sets are highly useful to efficiently remove duplicate values from a collection like a list and to perform common math operations like unions and intersections. * Sets are highly useful to efficiently remove duplicate values from a collection like a list and to perform common math operations like unions and intersections.
* We can use **casting** (remember) between lists and sets to remove dublicats from a list * We can use **casting** (remember) between lists and sets to remove dublicats from a list
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
my_list = [1,2,3,4,5,1,2,3,3] my_list = [1,2,3,4,5,1,2,3,3]
my_set = set(my_list) # remove duplicates by converting to set my_set = set(my_list) # remove duplicates by converting to set
print(my_set) print(my_set)
my_list = list(my_set) # convert back to list to make it mutable my_list = list(my_set) # convert back to list to make it mutable
print(my_list) print(my_list)
## Remove dublicates in one line ## Remove dublicates in one line
my_list = [1,2,3,4,5,1,2,3,3] my_list = [1,2,3,4,5,1,2,3,3]
my_list = list(set(my_list)) my_list = list(set(my_list))
print(my_list) print(my_list)
``` ```
%% Output %% Output
{1, 2, 3, 4, 5} {1, 2, 3, 4, 5}
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Dictionaries I ## Dictionaries I
* If we want to have a more dynamic and structured way to access information (especially nested information), dictionaries are a very useful concept. * If we want to have a more dynamic and structured way to access information (especially nested information), dictionaries are a very useful concept.
* Dictionaries to store data values in key:value pairs. * Dictionaries to store data values in key:value pairs.
* A dictionary is a collection which is ordered*, changeable and do not allow duplicates. * A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
* Dictionaries are written with curly brackets, and have keys and values, sepperated by a ```:``` * Dictionaries are written with curly brackets, and have keys and values, sepperated by a ```:```
* Keys are allways a String, e.g. ```"title"``` * Keys are allways a String, e.g. ```"title"```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
song = { song = {
"title" : "Another brick in the wall", "title" : "Another brick in the wall",
"artist" : "Pink Floyd", "artist" : "Pink Floyd",
"album" : "The Wall", "album" : "The Wall",
"year" : 1979 "year" : 1979
} }
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Dictionaries II ## Dictionaries II
* Since the key must be unike (like in a set), dublicates are not allowed. * Since the key must be unike (like in a set), dublicates are not allowed.
* Dicitionaries are accessd by the key in ```[]```or with the ```get()```method. * Dicitionaries are accessd by the key in ```[]```or with the ```get()```method.
* Teh advantage of the get method: If the key is not found, we can define a default value. * Teh advantage of the get method: If the key is not found, we can define a default value.
* With the ```keys()``` method, we can access all keys of a dictionary. * With the ```keys()``` method, we can access all keys of a dictionary.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
song = { song = {
"title" : "Another brick in the wall", "title" : "Another brick in the wall",
"artist" : "Pink Floyd", "artist" : "Pink Floyd",
"album" : "The Wall", "album" : "The Wall",
"year" : 1979 "year" : 1979
} }
print (song["title"]) print (song["title"])
print (song.get("title")) print (song.get("title"))
print (song.get("duration", "unknown")) print (song.get("duration", "unknown"))
print (song.keys()) print (song.keys())
``` ```
%% Output %% Output
Another brick in the wall Another brick in the wall
Another brick in the wall Another brick in the wall
unknown unknown
dict_keys(['title', 'artist', 'album', 'year']) dict_keys(['title', 'artist', 'album', 'year'])
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Important Methods of Dictionaries ## Important Methods of Dictionaries
* ```update()``` : change or add an item in/to the dictionary * ```update()``` : change or add an item in/to the dictionary
* ```pop()``` : remove an item from the dictionary * ```pop()``` : remove an item from the dictionary
* ```copy()``` : creates a copy (not an object reference) of the dictionary * ```copy()``` : creates a copy (not an object reference) of the dictionary
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
song = { song = {
"title" : "Another brick in the wall", "title" : "Another brick in the wall",
"artist" : "Pink Floyd", "artist" : "Pink Floyd",
"album" : "The Wall", "album" : "The Wall",
"year" : 1979 "year" : 1979
} }
song.update({"duration" : "3:30"}) # Add key-value pair song.update({"duration" : "3:30"}) # Add key-value pair
song.update({"year" : 1976}) # Update value song.update({"year" : 1976}) # Update value
song["tempo"] = 105 # Alternative way to add key-value pair song["tempo"] = 105 # Alternative way to add key-value pair
song.pop("album") # Remove key-value pair song.pop("album") # Remove key-value pair
print (song) print (song)
``` ```
%% Output %% Output
{'title': 'Another brick in the wall', 'artist': 'Pink Floyd', 'year': 1976, 'duration': '3:30', 'tempo': 105} {'title': 'Another brick in the wall', 'artist': 'Pink Floyd', 'year': 1976, 'duration': '3:30', 'tempo': 105}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Iterations on Dictionaries ## Iterations on Dictionaries
* When we do a ```for x in dict``` iteration * When we do a ```for x in dict``` iteration
* x will be the key the key for each key:value pair in the dicitonary * x will be the key the key for each key:value pair in the dicitonary
* If you prefer the values instead you can use the ```values()``` method of the dictionary * If you prefer the values instead you can use the ```values()``` method of the dictionary
* If you want both, keys and values: use the ``ìtems()``` method. * If you want both, keys and values: use the ``ìtems()``` method.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
song = { song = {
"title" : "Another brick in the wall", "title" : "Another brick in the wall",
"artist" : "Pink Floyd", "artist" : "Pink Floyd",
"album" : "The Wall", "album" : "The Wall",
"year" : 1979 "year" : 1979
} }
for key in song: for key in song:
print(key, end = ": ") print(key, end = ": ")
print(song[key], end = " | ") print(song[key], end = " | ")
print() print()
for value in song.values(): for value in song.values():
print(value, end = ", " ) print(value, end = ", " )
for key, value in song.items(): for key, value in song.items():
print(key, ": ", value) print(key, ": ", value)
``` ```
%% Output %% Output
title: Another brick in the wall | artist: Pink Floyd | album: The Wall | year: 1979 | title: Another brick in the wall | artist: Pink Floyd | album: The Wall | year: 1979 |
Another brick in the wall, Pink Floyd, The Wall, 1979, title : Another brick in the wall Another brick in the wall, Pink Floyd, The Wall, 1979, title : Another brick in the wall
artist : Pink Floyd artist : Pink Floyd
album : The Wall album : The Wall
year : 1979 year : 1979
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Nestet Dictionaries ## Nestet Dictionaries
* Link lists and tuples, dicitonaries can be nested * Link lists and tuples, dicitonaries can be nested
* But in contrast to lists, we can explain with the key, what the value is about * But in contrast to lists, we can explain with the key, what the value is about
* Thus, with dicitionaries we can build meaningful data strctures that can be processed by human and computers * Thus, with dicitionaries we can build meaningful data strctures that can be processed by human and computers
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
music_library = { music_library = {
"rock": { "rock": {
"band": "Led Zeppelin", "band": "Led Zeppelin",
"album": "IV", "album": "IV",
"year": 1971 "year": 1971
}, },
"jazz": { "jazz": {
"artist": "Miles Davis", "artist": "Miles Davis",
"album": "Kind of Blue", "album": "Kind of Blue",
"year": 1959 "year": 1959
}, },
"pop": { "pop": {
"artist": "Taylor Swift", "artist": "Taylor Swift",
"album": "1989", "album": "1989",
"year": 2014 "year": 2014
} }
} }
print(music_library["rock"]["band"]) print(music_library["rock"]["band"])
``` ```
%% Output %% Output
Led Zeppelin Led Zeppelin
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## For Geeeks: What does copy() really do? ## For Geeeks: What does copy() really do?
* Copying objets is often useful, when we want to update an object without loosing the original. * Copying objets is often useful, when we want to update an object without loosing the original.
* But is copy just a shallow copy of the first level or a deep copy? * But is copy just a shallow copy of the first level or a deep copy?
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
song = { song = {
"title" : "Another brick in the wall", "title" : "Another brick in the wall",
"artist" : "Pink Floyd" "artist" : "Pink Floyd"
} }
best_of_album = { "1" : song, "2" : { "title" : "Shine on you crazy diamond", "artist" : "Pink Floyd" }} best_of_album = { "1" : song, "2" : { "title" : "Shine on you crazy diamond", "artist" : "Pink Floyd" }}
other_album = best_of_album.copy() other_album = best_of_album.copy()
print(other_album) print(other_album)
song["title"] = "Wish you were here" # change the reference song["title"] = "Wish you were here" # change the reference
print(other_album) # song title is changed in both dictionaries, thus copy is shallow copy print(other_album) # song title is changed in both dictionaries, thus copy is shallow copy
``` ```
%% Output %% Output
{'1': {'title': 'Another brick in the wall', 'artist': 'Pink Floyd'}, '2': {'title': 'Shine on you crazy diamond', 'artist': 'Pink Floyd'}} {'1': {'title': 'Another brick in the wall', 'artist': 'Pink Floyd'}, '2': {'title': 'Shine on you crazy diamond', 'artist': 'Pink Floyd'}}
{'1': {'title': 'Wish you were here', 'artist': 'Pink Floyd'}, '2': {'title': 'Shine on you crazy diamond', 'artist': 'Pink Floyd'}} {'1': {'title': 'Wish you were here', 'artist': 'Pink Floyd'}, '2': {'title': 'Shine on you crazy diamond', 'artist': 'Pink Floyd'}}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## JSON ## JSON
* Dicitionaries in Phython are a representaiton of what we call a *data object*, more generally speaking * Dicitionaries in Phython are a representaiton of what we call a *data object*, more generally speaking
* In Java Script programming language we use exactly the same notation to create objects. * In Java Script programming language we use exactly the same notation to create objects.
* This notation is call JSON (Java Script Object Notation) * This notation is call JSON (Java Script Object Notation)
* If we use the kind on object notation as a means of communicaiton (e.g. in files or web communcation), we can very easily read these JSON strings an create data objects that can be processed directely in our code. * If we use the kind on object notation as a means of communicaiton (e.g. in files or web communcation), we can very easily read these JSON strings an create data objects that can be processed directely in our code.
* This is so convinient, that it has **become the standard in all kinds of data exchange**: RESTful Webservices, MQTT, Buisness-IT interfaces, Config files, ... * This is so convinient, that it has **become the standard in all kinds of data exchange**: RESTful Webservices, MQTT, Buisness-IT interfaces, Config files, ...
* In Python we can use the JSON module to do that. * In Python we can use the JSON module to do that.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import json import json
fileRow = '{"title" : "Another brick in the wall", "artist" : "Pink Floyd" }' fileRow = '{"title" : "Another brick in the wall", "artist" : "Pink Floyd" }'
song = json.loads(fileRow) song = json.loads(fileRow)
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment