DEV Community

Sakthivel V
Sakthivel V

Posted on

List operators in python

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"]
Enter fullscreen mode Exit fullscreen mode
  • insert() → Adds an item at a specific position. Ex:
fruits.insert(1, "mango")
print(fruits)   # ["apple", "mango", "banana", "cherry"]
Enter fullscreen mode Exit fullscreen mode
  • extend() → Adds multiple items from another list. Ex:
fruits.extend(["grape", "orange"])
print(fruits)   # ["apple", "mango", "banana", "cherry", "grape", "orange"]
Enter fullscreen mode Exit fullscreen mode

Delete():

  • pop() → Removes item by index (default: last item). Ex:
fruits.pop()        # removes "orange"
print(fruits)       # ["apple", "mango", "banana", "cherry", "grape"]
Enter fullscreen mode Exit fullscreen mode
  • remove() → Removes item by value. Ex:
fruits.remove("mango")
print(fruits)       # ["apple", "banana", "cherry", "grape"]

Enter fullscreen mode Exit fullscreen mode
  • clear() → Removes all items. Ex:
fruits.clear()
print(fruits)       # []
Enter fullscreen mode Exit fullscreen mode

Reorder():

  • sort() → Sorts items in ascending order. Ex:
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers)   # [1, 2, 5, 9]
Enter fullscreen mode Exit fullscreen mode
  • reverse() → Reverses the order of items. Ex:
numbers.reverse()
print(numbers)   # [9, 5, 2, 1]
Enter fullscreen mode Exit fullscreen mode

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) 

Enter fullscreen mode Exit fullscreen mode

Top comments (0)