Day 4 - Randomisation and Python Lists


Random Module
The random
module in Python is used to generate
random numbers or make random selections.
It is widely used for games, testing, and other
applications where randomization is needed.
Common Functions in the random
Module
1.random()
Generates a random floating-point number between 0.0
(inclusive) and 1.0
(exclusive).
Example:
import random
print(random.random())
Output
0.483475829
2. randint(a, b)
Generates a random integer between a
and b
(both inclusive).
Example:
print(random.randint(1, 10))
Output
Random number between 1 and 10
3.uniform(a, b)
Generates a random floating-point number between a
and b
.
Example
print(random.uniform(1.5, 5.5))
Output
Random float between 1.5 and 5.5
Use Cases
. Games: Randomizing player turns or shuffling cards.
. Testing: Generating test data.
Important Note
The numbers generated by the random
module are pseudo-random, meaning they are determined by an algorithm and are not truly random.
Understanding Offsets and Appending Items to the Lists
Understanding Offset (Index) in Lists
In Python, a list is an ordered collection of items, and each item has a position called an index or offset. The index starts at 0
for the first item in the list and increments by 1 for each item.
Key Points:
Indexing starts at 0:
First item: Index
0
Second item: Index
1
Last item: Index
-1
(negative indexing)
Accessing items using an offset:
You can retrieve an item by specifying its index within square brackets (
[]
).Example:
fruits = ['apple', 'banana', 'cherry'] print(fruits[0]) #Output: apple print(fruits[1]) #Output: banana print(fruits[-1]) #Output: cherry (last item)
- Out of range:
Accessing an index that doesn’t exist in the list raises an IndexError
.
Example:
(fruits[5]) # Raises IndexError
Appending Items to Lists
In Python, appending items to a list means adding new elements to the end of an existing list. Python lists are dynamic, so you can easily modify their size by adding items.
How to Append Items to Lists
Using the
append()
MethodThe
append()
method adds a single item to the end of a list.It does not create a new list; it modifies the original list in place.
Example:
numbers = [1, 2, 3]
numbers.append(4) # Adds 4 to the end of the list
print(numbers) # Output: [1, 2, 3, 4]
Appending a List as an Item
- You can append an entire list as a single item. In this case, the appended list becomes a nested list.
Example:
numbers = [1, 2, 3]
numbers.append([4, 5]) # Adds a nested list
print(numbers) # Output: [1, 2, 3, [4, 5]]
Appending Items from Another Iterable
Use the
extend()
method if you want to append multiple items from another iterable (like a list) to the current list.This adds the items individually, not as a nested list.
Example:
fruits = ['apple', 'banana']
fruits.extend(['cherry', 'orange']) # Adds multiple items
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
Key Differences:
append()
vsextend()
| Operation | Effect | Example | Result | | --- | --- | --- | --- | |
append(item)
| Addsitem
as a single element |list.append([4, 5])
|[1, 2, 3, [4, 5]]
| |extend(iterable)
| Adds each element fromiterable
|list.extend([4, 5])
|[1, 2, 3, 4, 5]
|
When to Use append()
When adding one item at a time.
When you want to add a nested list.
When to Use extend()
When adding multiple items from another iterable.
When you want to merge lists.
By understanding these methods, you can effectively grow and manipulate Python lists to suit your program's needs.
IndexErrors and Working with Nested Lists
IndexErrors in Python
An IndexError
occurs in Python when you try to access an element of a sequence
(such as a list
, tuple
, or string
) using an index that is out of range.
This means the index is either greater than the last index of the sequence or
less than the negative of the sequence's length.
What Causes IndexErrors?
Accessing an Index Greater Than the Sequence Length:
- If you try to access an index that is beyond the valid range, Python raises an
IndexError
.
- If you try to access an index that is beyond the valid range, Python raises an
my_list = [1, 2, 3]
print(my_list[3]) # IndexError: list index out of range
Using Negative Indices That Exceed the Range:
- Negative indices count from the end of a sequence. If the negative index exceeds the sequence's length, an
IndexError
occurs.
- Negative indices count from the end of a sequence. If the negative index exceeds the sequence's length, an
my_list = [1, 2, 3]
print(my_list[-4]) # IndexError: list index out of range
Accessing an Empty Sequence:
- An empty sequence (like an empty list) has no valid sequence.
empty_list = []
print(empty_list[0]) # IndexError: list index out of range
How to Avoid IndexErrors
Check the Length of the Sequence Before Accessing: Use the len()
function to ensure the index is within the valid range.
my_list = [1, 2, 3] index = 3 if index < len(my_list): print(my_list[index]) else: print("Index out of range!")
Examples of IndexErrors
Example 1: Accessing an Invalid Index
fruits = ["apple", "banana", "cherry"]
print(fruits[5]) # IndexError: list index out of range
Example 2: Negative Index Exceeding Range
numbers = [10, 20, 30]
print(numbers[-4]) # IndexError: list index out of range
Example 3: Empty List
empty_list = []
print(empty_list[0]) # IndexError: list index out of range
Key Takeaways
Always ensure indices are within the sequence's valid range.
Handle user inputs, dynamic indices, or uncertain data carefully to avoid unexpected errors.
Use tools like
len()
and loops to work safely with sequences.Where My Learning Takes Me Next
On Day 3 of the 100 Days of Python, I will learn about Python Loops.
Subscribe to my newsletter
Read articles from Muniba Amin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
