For Loops in Python
The for loop provides a clean way to iterate over containers with out relying on explicit index tracking. It executes a block of code for every item present in a collection.
Iteration Comparison: For vs. While
While while loops are suited for condition-based execution, for loops are designed for traversing collections. However, for loops can often mimic while behavior using the range() function.
# Example: Using range for fixed iterations
iteration_tracker = 0
for _ in range(5):
print(f"Current iteration: {iteration_tracker}")
iteration_tracker += 1
Visualizing Process Execution
You can create a simple loading animation by utilizing the end parameter in the print function too prevent line breaks, combined with time.sleep.
import time
print('Loading', end='')
for _ in range(6):
time.sleep(0.3)
print('.', end='')
Built-in Type Methods
Numerical Types (int, float)
Numeric types are immutable. They do not support indexing and therefore lack the concepts of order. Key operasions include:
- Modulo (
%) - Floor Division (
//) - Exponentiation (
**)
String Methods
Strings are ordered sequences and are immutable. Common operations include:
Essential Methods
- Indexing & Slicing:
text[0],text[start:stop:step] - Strip:
s.strip()removes whitespace or specific characters from both ends. - Split:
s.split(separator)converts a string into a list. - Length:
len(s)
Common Operations
- Case Manipulation:
.lower(),.upper(),.swapcase() - Joining:
' '.join(list_of_strings) - Replacement:
s.replace(old, new)(Returns a new string as strings are immutable). - Validation:
.isdigit(),.isalpha() - Searching:
.find()returns index or -1;.index()returns index or raises an error.
List Methods
Lists are mutable and ordered collections. They are highly flexible for data manipulation.
Key List Operations
- Mutation:
lst[i] = val - Addition:
.append(item)(add to end) or.insert(index, item)(add at position). - Removal:
.pop(index)or.remove(value). - Merging:
list_a.extend(list_b) - Sorting & Reversal:
.sort()sorts in-place;.reverse()flips list order.
Extending Built-in Classes
You can create custom functionality by subclassing built-in types. This leverages the underlying object-oriented architecture where methods are defined within classes and executed via instances.
class CustomList(list):
def bubble_sort(self):
n = len(self)
for i in range(n):
for j in range(0, n - i - 1):
if self[j] > self[j + 1]:
self[j], self[j + 1] = self[j + 1], self[j]
numbers = CustomList([5, 2, 9, 1])
numbers.bubble_sort()
print(numbers) # Output: [1, 2, 5, 9]