w3resource

Python: Remove the duplicate elements of a given array of numbers

Python Basic - 1: Exercise-73 with Solution

Write a Python program that removes duplicate elements from a given array of numbers so that each element appears only once and returns the new length of the array.

Sample Solution:

Python Code:

# Define a function to remove duplicates from a sorted list
def remove_duplicates(nums):
    # Iterate through the list in reverse order
    for i in range(len(nums)-1, 0, -1):
        # Check if the current element is equal to the previous one
        if nums[i] == nums[i-1]:
            # If equal, delete the previous element to remove the duplicate
            del nums[i-1]
    # Return the length of the modified list
    return len(nums)

# Test the function with two different lists and print the results
print(remove_duplicates([0,0,1,1,2,2,3,3,4,4,4]))  # [0, 1, 2, 3, 4], Length: 5
print(remove_duplicates([1, 2, 2, 3, 4, 4]))        # [1, 2, 3, 4], Length: 4

Sample Output:

5
4

Explanation:

Here is a breakdown of the above Python code:

  • First the function "remove_duplicates" takes a sorted list (nums) as input.
  • It iterates through the list in reverse order using a 'for' loop.
  • Inside the loop, it compares each element with its previous one to identify duplicates.
  • If a duplicate is found, it deletes the previous element using 'del' to remove the duplicate.
  • The function returns the length of the modified list after removing duplicates.
  • Test the function with two different lists and print the modified lists along with their lengths.

Visual Presentation:

Python: Remove the duplicate elements of a given array of numbers
Python: Remove the duplicate elements of a given array of numbers

Flowchart:

Flowchart: Python - Remove the duplicate elements of a given array of numbers

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to check whether a given integer is a palindrome or not.
Next: Write a Python program to calculate the maximum profit from selling and buying values of stock..

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.