How to use a single for loop In Python

Python3




# Python program to print duplicates from
# a list of integers
lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
 
uniqueList = []
duplicateList = []
 
for i in lis:
    if i not in uniqueList:
        uniqueList.append(i)
    elif i not in duplicateList:
        duplicateList.append(i)
 
print(duplicateList)


Output

[1, 2, 5, 9]

Time Complexity: O(n)
Auxiliary Space: O(n)

Python | Program to print duplicates from a list of integers

Given a list of integers with duplicate elements in it. The task is to generate another list, which contains only the duplicate elements. In simple words, the new list should contain elements that appear as more than one.

Examples:

Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output : output_list = [20, 30, -20, 60]
Input :  list = [-1, 1, -1, 8]
Output : output_list = [-1]

Similar Reads

Method 1: Using the Brute Force approach

Python3 # Python program to print # duplicates from a list # of integers def Repeat(x):     _size = len(x)     repeated = []     for i in range(_size):         k = i + 1         for j in range(k, _size):             if x[i] == x[j] and x[i] not in repeated:                 repeated.append(x[i])     return repeated   # Driver Code list1 = [10, 20, 30, 20, 20, 30, 40,          50, -20, 60, 60, -20, -20] print (Repeat(list1))       # This code is contributed # by Sandeep_anand...

Method 2: Using a single for loop

...

Method 3: Using Counter() function from collection module

Python3 # Python program to print duplicates from # a list of integers lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]   uniqueList = [] duplicateList = []   for i in lis:     if i not in uniqueList:         uniqueList.append(i)     elif i not in duplicateList:         duplicateList.append(i)   print(duplicateList)...

Method 4: Using count() method

...

Method 5: Using list comprehension method

Python3 from collections import Counter   l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9] d = Counter(l1) print(d)   new_list = list([item for item in d if d[item]>1]) print(new_list)...

Method 6: Using list-dictionary approach (without any inbuild count function)

...

Method 7: Using in, not in operators and count() method

Python3 # program to print duplicate numbers in a given list # provided input list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]   new = []  # defining output list   # condition for reviewing every # element of given input list for a in list:        # checking the occurrence of elements     n = list.count(a)       # if the occurrence is more than     # one we add it to the output list     if n > 1:           if new.count(a) == 0:  # condition to check               new.append(a)   print(new)   # This code is contributed by Himanshu Khune...