In this lesson we will go through advanced Python Types: Lists loops, For loop and While loop in detail.
In Python, lists are one of the most versatile and commonly used data structures. Lists allow you to store multiple items in a single variable, and they can contain items of different types (such as integers, strings, floats, or even other lists).
- Python Lists
– Definition: A list is an ordered collection of elements, which are enclosed in square brackets (`[]`) and separated by commas. Lists are mutable, meaning their elements can be changed, added, or removed.
– Syntax:
my_list = [element1, element2, element3, …]
– Examples:
numbers = [1, 2, 3, 4, 5] # List of integers
fruits = ["apple", "banana", "cherry"] # List of strings
mixed = [1, "hello", 3.14, True] # List with mixed data types
nested = [[1, 2], [3, 4], [5, 6]] # Nested list (list of lists)
Characteristics of Lists:
– Ordered: Elements in a list have a defined order, and this order will not change unless explicitly changed.
– Mutable: You can modify, add, and remove elements from a list after its creation.
– Heterogeneous: A list can contain elements of different types.
– Indexed: Elements in a list can be accessed using an index. Indexing starts at `0` for the first element, `1` for the second, and so on.
Common Operations on Lists:
- Accessing Elements:
– You can access elements using their index.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
– Negative indices can be used to access elements from the end of the list.
print(fruits[-1]) # Output: cherry
Modifying Elements:
– Lists are mutable, so you can change elements by accessing them via their index.
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
- Adding Elements:
– `append()`: Adds a single element to the end of the list.
fruits.append("mango")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'mango']
– `insert()`: Inserts an element at a specified index.
fruits.insert(1, "grape")
print(fruits) # Output: ['apple', 'grape', 'orange', 'cherry', 'mango']
- Removing Elements:
– `remove()`: Removes the first occurrence of a specified element.
fruits.remove("orange")
print(fruits) # Output: ['apple', 'grape', 'cherry', 'mango']
– `pop()`: Removes and returns the element at the specified index. If no index is provided, it removes and returns the last element.
last_fruit = fruits.pop()
print(last_fruit) # Output: mango
print(fruits) # Output: ['apple', 'grape', 'cherry']
- Slicing Lists:
– You can slice a list to obtain a sublist.
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[2:5]) # Output: [2, 3, 4]
print(numbers[:3]) # Output: [0, 1, 2]
print(numbers[4:]) # Output: [4, 5, 6]
print(numbers[-3:]) # Output: [4, 5, 6]
- Other Common List Methods:
– `sort()`: Sorts the list in place.
numbers.sort()
print(numbers) # Output: [0, 1, 2, 3, 4, 5, 6]
– `reverse()`: Reverses the order of the elements in the list.
numbers.reverse()
print(numbers) # Output: [6, 5, 4, 3, 2, 1, 0]
– `len()`: Returns the number of elements in the list.
print(len(fruits)) # Output: 3
Loops in Python: `for` Loop and `while` Loop
Loops are a fundamental programming concept that allows you to execute a block of code repeatedly based on a condition or a sequence. Python provides two main types of loops: the `for` loop and the `while` loop. Just observe the flow chart below for visualisation.

- `for` Loop
The `for` loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence.
– Syntax:
for item in sequence:
# Code block to execute for each item
– Description:
– `item` is a variable that takes the value of each element in the sequence during each iteration.
– `sequence` is any iterable object, such as a list, tuple, string, or range.
– Examples:
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
# Iterating over a range
for i in range(5): # range(5) generates numbers from 0 to 4
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
– Common Use Cases:
– Iterating over a List: Process or perform actions on each element.
– Iterating over a String: Loop through characters in a string.
– Using `range()`: Iterate over a sequence of numbers.
for i in range(1, 11): # Generates numbers from 1 to 10
print(i)
- `while` Loop
The `while` loop is used to repeatedly execute a block of code as long as a given condition is `True`. The loop stops when the condition becomes `False`.
– Syntax:
while condition:
# Code block to execute while the condition is True
– Description:
– `condition` is an expression that is evaluated before each iteration. If it is `True`, the loop continues; otherwise, it stops.
– The code block inside the `while` loop is executed repeatedly until the condition is `False`.
– Examples:
# Simple while loop
counter = 0
while counter < 5:
print(counter)
counter += 1
# Output:
# 0
# 1
# 2
# 3
# 4
# Using a while loop to sum numbers
total = 0
num = 1
while num <= 5:
total += num
num += 1
print(total) # Output: 15 (1 + 2 + 3 + 4 + 5)
– Common Use Cases:
– Condition-Based Repetition: Execute code repeatedly based on dynamic conditions (e.g., user input, state changes).
– Infinite Loops: Create loops that run indefinitely until a specific condition is met (e.g., `while True:`).
Using `break` and `continue` in Loops
– `break` Statement:
– Exits the loop immediately, regardless of the loop condition.
– Used to terminate the loop when a certain condition is met.
Python provides two keywords, `break` and `continue`, to control the flow of loops (`for` and `while` loops). These keywords help manage how the loop executes by allowing you to exit the loop prematurely (`break`) or skip to the next iteration (`continue`).
# 1. `break` Statement
The `break` statement is used to exit a loop before it has finished its normal iteration cycle. When `break` is encountered, the loop is immediately terminated, and the program continues with the next statement following the loop.
Use Case:
– Exiting a loop early when a certain condition is met.
– Searching for an element in a list and stopping when it’s found.
– Handling special cases within a loop.
Example of `break`:
# Example: Finding a number in a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num == 5:
print(f"Number {num} found!")
break # Exit the loop once number 5 is found
print(num)
Output:
1
2
3
4
Number 5 found!
Explanation:
The loop iterates through the list of numbers. When it reaches `5`, the `break` statement is executed, terminating the loop.
# 2. `continue` Statement
The `continue` statement is used to skip the current iteration of the loop and move to the next iteration. It does not terminate the loop but forces the next iteration to occur, ignoring the rest of the loop body below the `continue`.
Use Case:
– Skipping specific iterations based on a condition.
– Filtering data that doesn’t meet certain criteria.
– Skipping over errors or unwanted data without stopping the loop.
Example of `continue`:
# Example: Print odd numbers only
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0: # If the number is even
continue # Skip the rest of the loop body
print(num)
Output:
1
3
5
7
9
Explanation:
The loop iterates through the list. When an even number is encountered (`num % 2 == 0`), the `continue` statement is executed, skipping the `print(num)` statement and moving to the next iteration.
# Combining `break` and `continue`
Both `break` and `continue` can be used together within the same loop, but they serve different purposes. Here is an example where both are used:
Example:
# Example: Find the first odd number greater than 5
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num <= 5:
continue # Skip numbers less than or equal to 5
if num % 2 != 0: # Check for odd number
print(f"First odd number greater than 5 is: {num}")
break # Exit loop after finding the number
Output:
First odd number greater than 5 is: 7
Explanation:
The loop skips all numbers less than or equal to 5. When it encounters `7` (the first odd number greater than 5), it prints it and then uses `break` to exit the loop.
Summary
– `break` exits the loop entirely when a certain condition is met.
– `continue` skips the rest of the current loop iteration and moves to the next iteration.
These statements provide greater control over the loop flow, making Python code more flexible and efficient in handling various conditions.