diff --git a/curriculum/05-data-structures/01-list.md b/curriculum/05-data-structures/01-list.md new file mode 100644 index 0000000..64d3e43 --- /dev/null +++ b/curriculum/05-data-structures/01-list.md @@ -0,0 +1,168 @@ +--- +id: lists +title: List +sidebar_label: List +sidebar_position: 1 +lesson: true +isDraft: true +--- +# List +## Introduction {#introduction} +Up until now we have stored a single value in a variable, but what if we need to hold multiple values in some variable? Do we create multiple variables? Of course not, Python has a *built-in* mechanisms for dealing with collections of data which we call **data structures**. In this lesson we first take a look at **list**. + +Lists in Python are *built-in* data structure for storing ordered collections of items. They are **ordered** meaning they keep the order in which data came in. They are also **mutable** which means we can change them in place without creating a new copy. They can hold any other type of data including other lists or other data structures. Lists are probably the most used data structure in Python. + +## Lesson Overview {#overview} +In this lesson we will cover: +* What lists are? +* How to create a list? +* How to slice elements from the list? +* How to insert, modify or delete elements +* How to access elements +* Iterating over the lists using `for` loops + +## Creating lists +Lists in Python are created using **square brackets** (`[]`). They can be creates empty or already with some items provided (elements are separated by **comma** (`,`)) + +### Empty List +```python interactive +mylist = [] +print(f"Type of 'mylist' variable is: {type(mylist)}") +print(f"Value of 'mylist' is: {mylist}") +``` +### Pre-populated List +```python interactive +mylist = [1, 2, 3, 4] +print(f"Type of 'mylist' variable is: {type(mylist)}") +print(f"Value of 'mylist' is: {mylist}") +``` + +:::tip[Check the number of items (elements) in the list] + +You can use `len()` function to check the length of the list (and other types that support iteration). + +```python interactive +mylist = [1, 2, 3, 4] +list_length = len(mylist) +print(f"List has {list_length} elements") +``` +This function always returns **integer**. + +::: + +## Manipulating Elements in List +### Accessing Elements +To access the element withing a list we must use use its **index**. In Python we start counting from zero (0) so first element in the list is at index 0. Let's see this is example: +```python interactive +mylist = [1, 2, 3] +first_elem = mylist[0] +last_elem = mylist[-1] + +print(f"First element of the list is {first_elem} and last is {last_elem}") +``` + +:::tip[List slicing] +Similar how we use indexes, we can also cut our list (or elements within it) however we like. This is called **list slicing** and its a very effective way to get a subset of collection. + +It's syntax is `[start:stop:step]` (just like in **range()** function we learned in loops lesson). Let's see an example : +```python interactive +a = ["apple", "pear", "banana"] + +b = a[0:2] +print(a) +print(b) +``` +Result of `b` will be `["apple", "pear"]`. As you can see, slicing creates a new list with elements from the slice, while leaving original list with no changes. + +You can reverse a list by using negative step: +```python interactive +a = ["apple", "pear", "banana"] + +b = a[::-1] +print(a) +print(b) +``` + +In Python, **strings** behave like a *sequence types*, so you can do exact same slicing and dicing on the strings to get the characters out and they also support iteration. +```python interactive +a = "banana" +b = a[::-1] +print(b) +``` + +::: + +### Adding Elements +There are multiple ways to insert elements to the list, depending on where you want to place it. + +#### Method: `.append` +First example uses `.append()` method which takes a **single** argument and it is the recommended way of inserting elements. It adds them at the **last position**, expanding the list by one element, and does not need to recompute positiona of other elements, making it fast and reliable. Let's see an example: +```python interactive +a = [] # Empty list +print(f"List before appending: {a}") +a.append(2) +print(f"List after appending: {a}") +a.append(5) +print(f"List after another append: {a}") +``` + +#### Method: `.insert` +If you need to add elements at specific index, for that we use `.insert()` method which takes **two** arguments; *index* and *value*. This will insert *value* to supplied *index* shifting other elements to the right. Let's see this in the following example: +```python interactive +a = [1, 2, 3, 4] +print(f"List before insert: {a}") +a.insert(2, 5) # Insert value 5 to index 2 +print(f"List after insert: {a}") +``` + +### Removing Elements +Removing of elements can also be done in a couple of ways. + +In the first example we will use `.pop()` method that takes **one optional** argument; *index*. This method removes **and** returnes the element from the list. By default, it *pops* the last element but can be set with optional argument. +```python interactive +a = [1, 2, 3, 4] +print(f"List before pop: {a}") +b = a.pop() +print(f"List after pop: {a}, {b=}") + +# Pop some other element +c = a.pop(0) # Pop first element +print(f"List after another pop: {a}, {c=}") +``` + +Another way to remove an element is to use `.remove()` method, but unlike `.pop()` it requires **one** argument; *element*. This method is useful when you want to remove the specific element but do not know its index position and you dont care about the element afterwards. +```python interactive +a = [1, 2, 3, 4] +print(f"List before remove: {a}") +a.remove(3) +print(f"List after remove: {a}") +``` +### Iterating With Lists +Lists can be used with `for` loops to iterate on each element of the list, so you can proccess one at a time. Let's see how this works in the following example: +```python interactive +a = [1, 2, 3, 4] + +for item in a: + print(item) +``` +This is very useful as we often need to work with specific elements from the list. + +:::explore[Learn more about Python lists] + +Learn more about Python Lists from these resources: +* [Google for Education - Python Lists](https://developers.google.com/edu/python/lists) +* [Official Python Documentation on Lists](https://docs.python.org/3/library/stdtypes.html#typesseq-list) +* [Official Python Documentation on Data Structures - more on Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) + +::: + +## Exercise +Complete [Exercise 05 — The Cozy Bakery Inventory](#) to practice list creation, indexing, modification, and using python documentation to solve list tasks. + +## Assignment {#assignment} +**Todo** + +## What's Next {#next-lesson} +Lists are ordered and mutable, which makes them ideal for collections that grow or change over time. But what if you need an ordered collection that **cannot** be modified once created? + +In the next lesson, we will look at **Tuples** — Python's immutable data structure for storing fixed collections of data. \ No newline at end of file diff --git a/curriculum/05-data-structures/02-tuple.md b/curriculum/05-data-structures/02-tuple.md new file mode 100644 index 0000000..d97d13e --- /dev/null +++ b/curriculum/05-data-structures/02-tuple.md @@ -0,0 +1,63 @@ +--- +id: tuples +title: Tuple +sidebar_label: Tuple +sidebar_position: 2 +lesson: true +isDraft: true +--- +# Tuple +## Introduction {#introduction} +Tuple is an ordered and immutable collection data structure. **Ordered** meaning it keeps the order of elements in which they are inserted, and **immutable** means that once the tuple is created it cannot change, and you cannot add or remove elements from it. + +## Lesson Overview {#overview} +In this lesson we will cover: +* How to create tuple +* Accessing the elements in tuple +* Useful methods on tuples + +## Creating Tuple +A tuple is created by enclosing items in parentheses `()` separated by comma. +```python interactive +a = (1, 2, 3) +print(f"Variable a contains type: {type(a)} and the value of variable is: {a}") +``` +Tuples containing a single element still must contain a comma, otherwise python will read the wrong data type: +```python interactive +a = (1) +b = (1,) + +print(f"Type of variable a is: {type(a)}") +print(f"Type of variable b is: {type(b)}") +``` + +## Accessing Elements +Accessing elements of the tuple is done with index, just like lists. +```python interactive +a = (1, 2, 3) +print(f"First element: {a[0]} - Last element: {a[-1]}") +``` + +## Useful methods +Unlike functions, as we cannot modify tuples, we don't have a lot of methods available to us, but we will list a few. +* `count()` - returns the number of times a specified value appears in tuple. + ```python interactive + numbers = (1, 2, 3, 3, 3, 4, 5) + print(numbers.count(3)) + ``` +* `index()` - returns index of the **first occurrence** of the element. + ```python interactive + fruits = ("apple", "banana", "cherry") + print(fruits.index("banana")) + ``` + +:::explore[Learn more about Python Tuples] +* [Python built-in types: tuples from RealPython](https://realpython.com/ref/builtin-types/tuple/) +* [Tuples and Sequences from official Python documentation](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences) +::: + +## Assignment {#assignment} +**Todo** + +## What's Next {#next-lesson} +**Todo** \ No newline at end of file diff --git a/curriculum/05-data-structures/03-set.md b/curriculum/05-data-structures/03-set.md new file mode 100644 index 0000000..e172981 --- /dev/null +++ b/curriculum/05-data-structures/03-set.md @@ -0,0 +1,85 @@ +--- +id: set +title: Set +sidebar_label: Set +sidebar_position: 3 +lesson: true +isDraft: true +--- +# Set +## Introduction {#introduction} +A **set** in Python is unordered collection of unique elements. **Unordered** means it does not keep the order of the elements and **unique** means it does not allow duplicates. + +Its mostly used when removing duplicates from list or performing quick membership tests (checking to see if some element belongs to both sets). + +## Lesson Overview {#overview} +In this lesson we will cover: +* How to create set +* How to access elements of the set +* Adding or removing elements +* Set operations + +## Creating Set +Creating sets in Python is done with curly braces `{}` or its constructor `set()`. +```python interactive +# Using curly braces +myset = {1, 2, 2, 2, 3, 3, 4, 5} +print(f"Type of variable myset is: {type(myset)} and the value is: {myset}") + +# Using set() function +other_set = set([1, 1, 2, 2, 3, 4, 5,5]) +print(f"Type of variable other_set is: {type(other_set)} and the value is: {other_set}") +``` +To create an empty set, we need to use `set()` function as using `{}` will create a new dictionary (which we will cover in the next lesson). + +## Accessing Elements +We cannot access elements of the set like we did with other data structures using index, but we can iterate over it with `for` loop or check if the item exists with `in` keyword : +```python interactive +myset = {1, 2, 2, 2, 3, 3, 4, 5} + +for item in myset: + print(item) + +print(f"Is 3 in set?: {3 in myset}") +``` + +## Adding and Removing Elements +We can use `.add()` method to add a single element to set or use `.update()` method to add multiple elements. +```python interactive +a = {1, 2, 3} +a.add(4) +print(f"Set after add: {a}") + +a.update([5, 6, 7]) +print(f"Set after update: {a}") +``` + +Removing the elements can be done with `.remove()` method which raises `KeyError` if that element does not exist. +```python interactive +a = {1, 2, 3} +a.remove(2) +print(f"Set after remove: {a}") +``` + +## Set Operations +Sets support mathematical operations like union, intersection, and difference, making them useful for comparing collections. +```python interactive +set1 = {1, 2, 3} +set2 = {3, 4, 5} + +print("Union:", set1 | set2) +print("Intersection:", set1 & set2) +print("Difference:", set1 - set2) +``` + +:::explore[Learn more about Python Sets] +Learn more about sets in these materials: +* [Python built-in data types from RealPython](https://realpython.com/ref/builtin-types/set/) +* [Python data structures: set from official Python documentation](https://docs.python.org/3/tutorial/datastructures.html#sets) +::: + +## Assignment {#assignment} +**Todo** + +## What's Next {#next-lesson} +**Todo** \ No newline at end of file diff --git a/curriculum/05-data-structures/04-dictionary.md b/curriculum/05-data-structures/04-dictionary.md new file mode 100644 index 0000000..7b6378b --- /dev/null +++ b/curriculum/05-data-structures/04-dictionary.md @@ -0,0 +1,135 @@ +--- +id: dictionary +title: Dictionary +sidebar_label: Dictionary +sidebar_position: 4 +lesson: true +isDraft: true +--- +# Dictionary +## Introduction {#introduction} +Dictionaries in Python are mutable and unordered collection data structure. **Mutable** meaning it can be modified after creating and **unordered** meaning it does not keep track of it's elements. + +Dictionaries are something special, usually called **key-value** data structure because of the way you store data inside them. You will certanly do a lot of work involving dictionaries in your python applications and its a very powerful concept, so let's get started. + +## Lesson Overview {#overview} +In this lesson you will learn: +* How to create a dictionary +* How to manipulate elements +* How to iterate over dict + +## Dictionary +### Creating Dictionary +We create a **dictionary** in Python using curly braces `{}`. It consists of two values; **key** and **value**. **Key** is what you use to access the element and **value** is what that element holds. +Let's see an example: +```python interactive +mydict = {"key": "value"} +print(f"Type of variable mydict is: {type(mydict)} and value is: {mydict}") +``` +Keys can be any **imutable** type like strings, integers, floats, tuples, etc... +Values can be practicly anything, from simple strings and numbers to complex lists, other dictionaries or any combinations which you want and need. +To separate elements (key-value pairs), use comma `,`. + +### Accessing Elements +Accessing an element in a dictionary is done with `[]` syntax but unlike *indexes* we used before, now we use **key** of the element to retrive it. + +If the key does not exists, Python will raise **KeyError**. We can get around that by using `.get()` method which is safer to use as it does not raise an error, but returns `None` (by default) if the key does not exists. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} +value1 = mydict["key1"] +print(value1) + +# Safer and recommended approach +value2 = mydict.get("key2") +print(value2) +``` + +### Updating Elements +Updating elements is as simple as assigment of a new value to existing key. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} +print(f"Before: {mydict}") +mydict["key1"] = "other value" +print(f"After: {mydict}") +``` + +### Adding Elements +Adding new elements to dictionary is done just like *updating* but we use *key* that is **not** already in the dictionary. +```python interactive +mydict = {"key1": "value1"} +print(f"Before: {mydict}") +mydict["key2"] = "other value" +print(f"After: {mydict}") +``` + +### Removing Elements +To remove and return the value of the element from dictionary you can use `.pop()` method which takes in a single argument; **key**. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} +print(f"Before: {mydict}") +poped_value = mydict.pop("key1") +print(poped_value) +print(f"After: {mydict}") +``` + +You can also use `del`keyword to remove a key-value pair from the dictionary. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} +print(f"Before: {mydict}") +del mydict["key1"] +print(f"After: {mydict}") +``` + +For clearing the whole dictionary content you can use `.clear()` method. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} +print(f"Before: {mydict}") +mydict.clear() +print(f"After: {mydict}") +``` + +### Iterating Over Elements +Its common to iterate over dictionaries to check if it contains some specific values or simply using elements one by one. Dictionaries have two methods that help with this. + +Let's go over what happens when you iterate over a dictionary by itself. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} + +for elem in mydict: + print(elem) +``` +We would expect to get both keys and values, but you can see, that is not the case. This only returnes keys present in the dictionary. + +You can also use `.keys()` method to get the same result. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} + +for elem in mydict.keys(): + print(elem) +``` + +While it can be useful, we usually want to grab values, or both keys and values. To grab just values contained we can use `.values()` method which does exactly that. +```python interactive +mydict = {"key1": "value1", "key2":"value2"} + +for value in mydict.values(): + print(value) +``` + +To grab both keys and values, we can use `.items()` method. This method returnes 2 values which we can unpack directly to `key` and `value` pairs (these are just variables, so you can name them whatever you want). +```python interactive +mydict = {"key1": "value1", "key2":"value2"} + +for key, value in mydict.items(): + print(key, value) +``` + + + +## Assignment {#assignment} + + +## Deepen Your Knowlege {#learn-more} + + +## What's Next {#next-lesson} \ No newline at end of file diff --git a/curriculum/05-data-structures/_category_.json b/curriculum/05-data-structures/_category_.json new file mode 100644 index 0000000..42071f1 --- /dev/null +++ b/curriculum/05-data-structures/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Data Structures", + "position": 5, + "link": { + "type": "generated-index", + "description": "Holding multiple data in varius containers" + } +}