Remove element from a Python list

If we want to remove all the elements from the list, we use a clear function to remove the entire data in the list. In this article, we will clarify the concept of a Python list.

This is how to remove all elements from the list.

Using Python Remove()

Code

my_list = [1, 2, 3, 4, 5]

# Remove element 3 from the list
my_list.remove(3)

print(my_list) 

Output

Output: [1, 2, 4, 5]

Using Del Statement

Code

my_list = [1, 2, 3, 4, 5]

# Remove element at index 2 from the list
del my_list[2]

print(my_list) 

Output

Output: [1, 2, 4, 5]

How do we sort elements of a list?

We have two methods to sort a list among them. First, we use a logical way to sort the elements of the list.

Below is the code to sort the given list.

Code

def bubble_sort(arr):
    n = len(arr)

    # Traverse through all array elements
    for i in range(n - 1):
        # Last i elements are already in place
        for j in range(n - i - 1):
            # Swap if the current element is greater than the next element
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Example usage
my_list = [5, 2, 9, 1, 7]
bubble_sort(my_list)
print(my_list)  

Output

Output: [1, 2, 5, 7, 9]

Explanation

the above approach is called a bubble sort algorithm.

Let us discuss all the methods that are used listed in brief:

  • Append()à This function is used to insert the element at the end of the list.
  • Insert()à This function inserts the element at the required position.
  • Sort()à This function is used to sort the elements of the list.
  • Reverse()à This function is used to reverse the list.
  • Clear()àthis function will clear all the elements in the list.
  • Pop() à This function removes the element from the list at the required position.
  • Remove() àthis function is used to remove a specific element from the list.
  • Count()à This function will return the number of times a value has occurred in the list.
  • Max()àit will give the maximum element in the list.
  • Min()àit will give the minimum element in the list.

Note:- Choose the appropriate method based on whether you know the value or the index of the element you want to remove from the list.