0

A very odd and peculiar thing happened. I was trying to answer the question at Compare 1 column of 2D array and remove duplicates Python and I made the following answer (which I did not post since some of the existing answers to that question are much compact and efficient) but this is the code I made:

array = [['abc',2,3,],
        ['abc',2,3],
        ['bb',5,5],
        ['bb',4,6],
        ['sa',3,5],
        ['tt',2,1]]

temp = []
temp2 = []

for item in array:
    temp.append(item[0])

temp2 = list(set(temp))

x = 0
for item in temp2:
    x = 0
    for i in temp:
        if item == i:
            x+=1
        if x >= 2:
            while i in temp:
                temp.remove(i)

for u in array:
    for item in array:
        if item[0] not in temp:
            array.remove(item)

print(array)

The code should work, doing what the asker at the given link requested. But I get two pairs of results:

[['sa', 3, 5], ['tt', 2, 1]]

And

[['bb', 4, 6], ['tt', 2, 1]]

Why does the same code on the same operating system on the same compiler on the same everything produce two different answers when run? Note: the results do not alternate. It is random between the two possible outputs I listed above.

2
  • You're iterating over temp and array while removing values out of them. Is this what you want? Commented Jan 22, 2017 at 14:16
  • Ah! Thank you @ForceBru. If you post as an answer I can mark as correct. Commented Jan 22, 2017 at 14:20

1 Answer 1

4

In Python sets don't have any specific order, i.e. the implementation is free to choose any order and hence it could be different for each program run.

You convert to a set here:

temp2 = list(set(temp))

Ordering the result should give you consistent (but maybe not right) results :

temp2 = sorted(set(temp))

My results for array.

Sorted:

temp2 = sorted(set(temp))

array looks like this:

[['bb', 4, 6], ['tt', 2, 1]]

Reversed:

temp2 = sorted(set(temp), reverse=True)

array looks like this:

[['sa', 3, 5], ['tt', 2, 1]]
Sign up to request clarification or add additional context in comments.

Comments

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.