Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 168 additions & 0 deletions curriculum/05-data-structures/01-list.md
Original file line number Diff line number Diff line change
@@ -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.
63 changes: 63 additions & 0 deletions curriculum/05-data-structures/02-tuple.md
Original file line number Diff line number Diff line change
@@ -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**
85 changes: 85 additions & 0 deletions curriculum/05-data-structures/03-set.md
Original file line number Diff line number Diff line change
@@ -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**
Loading
Loading