List operators:
- In Python, lists are very flexible. We can add new items, delete items, and reorder items
- There are several kinds of list operations,they are:
- Add()
- Delete()
- Reorder()
Add():
- append() → Adds an item at the end. Ex:
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ["apple", "banana", "cherry"]
- insert() → Adds an item at a specific position. Ex:
fruits.insert(1, "mango")
print(fruits) # ["apple", "mango", "banana", "cherry"]
- extend() → Adds multiple items from another list. Ex:
fruits.extend(["grape", "orange"])
print(fruits) # ["apple", "mango", "banana", "cherry", "grape", "orange"]
Delete():
- pop() → Removes item by index (default: last item). Ex:
fruits.pop() # removes "orange"
print(fruits) # ["apple", "mango", "banana", "cherry", "grape"]
- remove() → Removes item by value. Ex:
fruits.remove("mango")
print(fruits) # ["apple", "banana", "cherry", "grape"]
- clear() → Removes all items. Ex:
fruits.clear()
print(fruits) # []
Reorder():
- sort() → Sorts items in ascending order. Ex:
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers) # [1, 2, 5, 9]
- reverse() → Reverses the order of items. Ex:
numbers.reverse()
print(numbers) # [9, 5, 2, 1]
Bubble Sort Algorithm:
- Bubble Sort is one of the easiest sorting methods.
- It works by repeatedly comparing two items side by side and swapping them if they are in the wrong order.
- After each iteration, the biggest number “bubbles up” to the end of the list.
How Bubble Sort Works:
- Start at the beginning of the list.
- Compare the first two items.
- If the first is bigger, swap them.
- Move to the next pair and repeat.
- Keep doing this until the end of the list.
- After one pass, the largest item is at the end.
- Repeat the process for the remaining items until the whole list is sorted.
Python code:
a = [7, 12, 9, 11, 3]
for i in range(len(a)):
for j in range(len(a) - 1):
if a[j] > a[j + 1]:
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
print("Sorted list:", a)

Top comments (0)