Python Notes PDF
Python Notes PDF
We are looping through a sequence (like a string or list) and counting how many times
something appears.
Output:
Number of a's: 3
But a loop gives We more control if We're doing multiple things at once.
Summary
Task How to do it
Loop over string/list for item in sequence:
Count with condition if item == target: count += 1
Count directly sequence.count(target)
Example:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True]
Removing Values
fruits.remove("apple") # Remove by value
fruits.pop() # Remove last item
print(len(numbers)) # 4
print(numbers.count(2)) # 1
numbers.sort() # [1, 2, 5, 9]
numbers.reverse() # [9, 5, 2, 1]
Summary
Action Code Example
Access value my_list[0]
Modify value my_list[1] = "new"
Add value my_list.append("new")
Remove value my_list.remove("old")
Loop through for x in my_list:
Count values my_list.count("x")
Accessing Elements in Python:
We can access individual elements of sequences like lists or strings using indexing.
Basic Indexing
my_list = ["apple", "banana", "cherry"]
print(my_list[0]) # apple
print(my_list[1]) # banana
print(my_list[2]) # cherry
• Indexing starts at 0
• So my_list[0] is the first item
Negative Indexing
We can also use negative numbers to start counting from the end:
print(my_list[-1]) # cherry (last item)
print(my_list[-2]) # banana
Accessing in Loops
To go through each element, use a loop:
for item in my_list:
print(item)