Instagram
youtube
Facebook
Twitter

Python Program to Find Duplicate Numbers in a List from 1 to 100

A Python Program to Find Duplicate Numbers in a List from 1 to 100?

Code Explanation:

Function Definition:
A function find_duplicates(nums) is defined to find all duplicate elements in a list.

Initialize Data Structures:
duplicates = [] is an empty list to store duplicate values.
seen = set() is used to keep track of numbers already encountered.

Loop Through the List:
The program loops through each number in the input list nums.

Check for Duplicates:
If a number is already in the seen set and not already in the duplicates list, it is added to duplicates.

Add to Seen Set:
If the number is not a duplicate, it is added to the seen set.

Return Result:
After the loop, the duplicates list containing all duplicate numbers is returned.

Input List:
A predefined list numbers with some duplicate values is given.

Function Call and Output:
The function is called with the list, and the result is printed as the list of duplicate numbers.

 

Program:

def find_duplicates(nums):

    duplicates = []

    seen = set()

    for num in nums:

        if num in seen and num not in duplicates:

            duplicates.append(num)

        else:

            seen.add(num)

    return duplicates

numbers = [1, 2, 3, 4, 5, 6, 3, 7, 8, 9, 2, 10, 4, 11, 12]

result = find_duplicates(numbers)

print("Duplicate numbers:", result)