Python: Lists and Loops
Python Lists and Loops
1 Overview
📘 Lists and Loops in Python
Lists in Python are mutable, ordered sequences that can hold elements of different types, support indexing, and allow modifications like adding, removing, and changing items. Loops in Python, such as for and while, are control flow constructs that repeatedly execute a block of code over collections like lists or as long as a condition is met.
2 Lists
- Ordered collection.
- Enclosed in square brackets and separated by commas.
- It is allowed to store elements from multiple types.
3 Indexing and slicing
- Indexing and slicing works like in strings.
7
[4, 3, 2]
[1, 3, 7]
4 Operations
- Like strings as well, with
+for concatenation and*for repetition.
4.1 Empty
- Check if a list is empty with
len,not, and[].
5 Updating
- Lists are mutable (unlike strings)!
6 Adding elements
We can add elements to a list using:
append(): Adds an element to the end of the list.
extend(): Adds multiple elements to the end of the list.
insert(): Adds an element at a specific index.
7 Removing elements
To remove elements from a list:
remove(): Deletes the first occurrence of a specified element.
- It crashes if there is no equal element…
pop(): Removes an element at a given index.
- If the index is not specified, it deletes the last element.
- The removed element is returned.
- We can optionally store it in a variable.
[1, 2, ‘a’, 3, 2]
7.1 When to use each?
remove(): When you only want to remove the first occurrence of an element.pop(): When you want to remove by index and preserve the value in a variable.Also comfortable when you want to remove the last element.
del: When you want to remove by index. It is a bit more efficient thanpop().
You could also use
pop()without storing the returned value though…
8 Other list methods
Some of the most common are:
index(): Returns the index of the first occurrence of a specified element in the list.
The index of the first occurrence of 2 is: 1.
count(): Counts the number of occurrences of a specified element in the list.
print(f’The number 2 appears {my_list.count(2)} times.’)
<div class="output">The number 2 appears 4 times.</div>
***
- `sort()`: Sorts the elements of the list in-place (modifies the original list).
<!-- - `reverse()`: Reverses the elements of the list in-place (modifies the original list).
- `copy()`: Returns a copy of the list. -->
```python
my_list = [1, 2, 2, 2, 3, 4, 2, 5]
my_list.sort()
print(my_list)
- Extensive explanation of list methods: https://docs.python.org/3/tutorial/datastructures.html.
9 Built-in functions
Some of the most common general built-in functions for lists are:
len(): Returns the number of elements in a list.sum(): Returns the sum of all elements in a list (for numeric lists).max(): Returns the maximum value in a list.min(): Returns the minimum value in a list.sorted(): Returns a sorted list (does not modify the original list).
my_list = [1, 4, 2, 7, 3]
print(f'The length of the list is: {len(my_list)}.')
print(f'The sum of all the elements is: {sum(my_list)}.')
print(f'The maximum element is: {max(my_list)}.')
# Unlike the `sort()` method,
# `sorted()` returns another list without modifying the original one
print(f'The list sorted in ascending order is: {sorted(my_list)}.')The sum of all the elements is: 17.
The maximum element is: 7.
The list sorted in ascending order is: [1, 2, 3, 4, 7].
- What is printed?
- When setting a list as equal to another, both variables affect the same list.
b = [8, 2, 3]
- If we want independent lists we can use the
copy()method:
b = [8, 2, 3]
10 in Keyword
- Can be used for checking if a specific value is inside the sequence.
- It also has a special usage in “for loops” (next slides).
11 Loops
- Essential in programming.
- They allow us to execute a block of code repeatedly.
- Python supports two types:
forandwhileloops.
11.1 for
Iterate over a sequence, such as a list or a string.
Syntax:
for [variable_name] in [iterable_sequence]: code block
11.2 List iteration example
2
3
Commonly used built-in functions for for loops:
enumerate(): Gives back two variables: the count of the current iteration and the value of the item at the current iteration.
The element at index 1 is 2.
The element at index 2 is 1.
range(): Sequence of numbers. By default, starts from 0 and increments by 1. Stops before a specified number.
1
2
3
3
4
5
2
4
6
8
11.3 String iteration example
e
l
l
o
11.4 While
Executes an iteration if condition remains
True.Syntax:
while [condition]: code block
1 is less than 4.
2 is less than 4.
3 is less than 4.
The loop ended because 4 is greater or equal to 4.
- We can chain as many conditions as we want:
1 is less than 4 and 3 is less than 8.
2 is less than 4 and 6 is less than 8.
3 is greater or equal to 4 or 9 is greater than 8.
- Take care of infinite loops!
- If the specified condition is never met,
whilewill execute forever… - Raising a Python error (maybe after some time!).
12 Example
- Create a list that contains the squares of the first 5 integers.
13 List comprehension
List comprehension is a concise way to create a new list by performing an operation on every element of an existing iterable (like a list, tuple, or range). It can also include a condition to filter which items are included. The Syntax:
newlist = [expression for item in iterable if condition == True]
*The return value is a new list, leaving the old list unchanged.
expression: What you want to do with each item (e.g., multiply by 2).item: The current element from the iterable.iterable: The list, range, or other object you are looping over.if condition: (optional) Only include items that meet this condition.
{pyodide-python numbers = [1, 2, 3, 4] doubled_numbers = [num * 2 for num in numbers] print(doubled_numbers)
In this example, num * 2 is the expression, num is each item from numbers, and numbers is the iterable.
14 Loop control statements
Allow us to change the flow of loops during execution.
Keywords:
break: Terminates the current loop.continue: Skips the remaining code in the current iteration and proceeds to the next one.
1
2
3
4
Outside the loop
3
5
7
9
Outside the loop
15 Unpacking
- Taking the elements of a collection (list, string…) and assigning them to variables.
4
16 Unpacking
- Another example with strings.
e
y
17 Example
Write a program that finds the common elements between two lists with the same length.
Input:
list1 = [1, 2, 3, 4, 5]list2 = [4, 5, 6, 7, 8]
Output:
[4, 5]
