Octo
Octo

Reputation: 727

Python different results from same code

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.

Upvotes: 0

Views: 2636

Answers (1)

Mike Müller
Mike Müller

Reputation: 85442

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]]

Upvotes: 4

Related Questions