1
list = [1,1,3,4,5,5,5,6]
count = 0
for i in range(len(list)):
    for k in range(len(list)):
        if i == k :
            continue
        elif list[i] == list[k]:
            del list[k]
            list.append("0")
            count = count + 1

print(count)
print(list)

When I execute this , "0" values added to this List for fill deleted duplicated values . I used count variable for count it , Count variable Supposed to print 3 , because when I run the program , 3 of "0" added to list. It Print "9" why?

This is the output

9
  • 5
    Why use for loop? why not set, i.e., my_set = set(my_list); count = len(my_set) - len(my_list) Commented Sep 13, 2021 at 3:56
  • @Chris my expected output is 3 for count variable , because three "0" s added to the list , But Count variable Prints "9" Commented Sep 13, 2021 at 4:00
  • @RaviJoshi Using set is Easy , But I wanted to do using for loops for practice Commented Sep 13, 2021 at 4:01
  • you have to use for k in range(i, len(list)) otherwise you will compare with previous value from the lsit Commented Sep 13, 2021 at 4:02
  • and it is very recommended that you give a name other than list to your list, since list is a python method Commented Sep 13, 2021 at 4:03

5 Answers 5

2

When you remove a number and add a zero to the end of the list, your main loop (for i ...) will eventually get to the zeroes at the end. At that point you will have removed one '1' and two '5' so the count will be 3 and there will be 3 zeroes to process. Each of these zeroes will find two other zeroes in the list (replacement with another zero wont make a difference). So, in total 1+2+2+2+2 = 9 counting 1 (for the 1's) 2 (for the 5's) and three more times 2 (for each of the zeroes).

One way around this (without changing your code too much) would be to break the main loop when you reach a zero (assuming zero is not a legitimate value in the initial list)

Sign up to request clarification or add additional context in comments.

Comments

1

You will have to forgive me if I have this wrong, but from your example, you were adding a "0" for each duplicated number and then trying to count how many "0's" had been added to the list.

Creating a set based on the list would seem easier, and then comparing the two to my way of thinking.

mylist = [1,1,3,4,5,5,5,6]

myset = set(mylist)

print(len(mylist) - len(myset))

This would give you the answer of 3 that you were looking for.

1 Comment

Yes , Using Sets is the best way to remove Duplicates , I just wanted to mess with for-loops for practice
1

Logic error.

  1. If you intend to replace the duplicate values with 0, then performing a del + list.append() is incorrect because del with remove the value while list.append() will add a new value at the end of the list, not inline. See this example.
my_list = [100, 100, 200]
print(my_list, "Original list")

del my_list[1]
print(my_list, "List after del")

my_list.append(0)
print(my_list, "List after append")

Output:

[100, 100, 200] Original list
[100, 200] List after del
[100, 200, 0] List after append

You can use del + list.insert(), but that is still inefficient. Instead, what you have to do is just re-assign the new value directly.

my_list[1] = 0
print(my_list, "List after re-assignment")

Output:

[100, 0, 200] List after re-assignment
  1. For every element, you are iterating all other elements but skips the current element itself. This means that if you changed a value to 0 in the next elements, once you reach that element, it would then count the other zeros as duplicates, even if those aren't meant to be counted. So pseudocode would be:
[100, 100, 200, 200] -> Original list

loop index=0
    Check duplicates for item-0 which is 100
    [100, 0, 200, 200] -> Sees item-1 as duplicate.
    count = 1
loop index=1
    Check duplicates for item-1 which is 0
    No duplicates
    count = 1
loop index=2
    Check duplicates for item-2 which is 200
    [100, 0, 200, 0] -> Sees item-3 as duplicate.
    count = 2
loop index=3
    Check duplicates for item-3 which is 0
    [100, 0, 200, 0] -> Sees item-1 as duplicate.
    count = 3

As you can see, it incorrectly counts the duplicate value of 0. A quick fix to your code is to skip the 0 elements

...
for i in range(len(list)):
    if list[i] == 0:
        continue
    ...

Better yet, redesign the logic. Instead of iterating over all elements, just iterate up to the current element only. So the idea is to loop over each element, and check if it already occurred in the past elements. To emphasize, past elements, don't iterate yet on the future elements.

  1. Don't use the builtin name list. This will cause failure if you then write list(some_iterable) later.

Sample solution

my_list = [1,1,3,4,5,5,5,6]
count = 0
for i in range(len(my_list)):
    for k in range(0, i):
        if my_list[i] == my_list[k]:
            my_list[i] = 0  # If you want the result to be [1, 0, 3, 4, 5, 0, 0, 6]
            # my_list[k] = 0  # If you want the result to be [0, 1, 3, 4, 0, 0, 5, 6]
            count = count + 1
            break

print(count)
print(my_list)

Output

3
[1, 0, 3, 4, 5, 0, 0, 6]

Improvement

Note that your algorithm has a time complexity of O(n^2). You can lower it down to O(n) by using additional O(n) space complexity which will track already existing elements.

my_list = [1,1,3,4,5,5,5,6]
existing = set()
count = 0
for i in range(len(my_list)):
    if my_list[i] in existing:
        my_list[i] = 0
        count += 1
    else:
        existing.add(my_list[i])

print(count)
print(my_list)

1 Comment

Thank you very much ! , This is the best explanation I've ever had
0
ls = [1,1,3,4,5,5,5,6]
result = []
for item in ls[:]:
    if item not in result:
        result.append(item)

print(result)

2 Comments

This is the best way to do it , But I did my code for practice nested-loops
A better way to do this is using a List comprehension
0

to use for loop try the below code:

# old list 
mylist = [1,1,3,4,5,5,5,6]
# create new list
newlist = []

# Loop for each item inside the old list 
for x in mylist:
    #check if this item is not duplicate 
    if x not in newlist:
        # add not duplicate item to new list
        newlist.append(x)

print (newlist)

Output:-

[1, 3, 4, 5, 6]

1 Comment

Thank you , This is the best way to do it , But I did my code for practice nested-loops ,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.