VOOZH about

URL: https://dev.to/sakthivenkat/list-operators-in-python-1bn5

⇱ List operators in python - DEV Community


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:
  1. Add()
  2. Delete()
  3. 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:

  1. Start at the beginning of the list.
  2. Compare the first two items.
  3. If the first is bigger, swap them.
  4. Move to the next pair and repeat.
  5. Keep doing this until the end of the list.
  6. After one pass, the largest item is at the end.
  7. 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)