Reputation: 336
I have a list with tuples [(a,b,c,1),(e,a,a,0),etc.]
, where each tuple consists of three strings and an integer. Each value is stored in unicode, i.e. (u'a',u'b',u'c',1)
.
My list contains 98 unique tuples. For 3 of them the following holds:
tuple[2] == "SUPPLEMENTARY PLUMPY",
namely:
(u'FRANCE', u'ROUEN (FRANCE)', u'SUPPLEMENTARY PLUMPY', 0)
(u'INDIA', u'MUMBAI (INDIA)', u'SUPPLEMENTARY PLUMPY', 0)
(u'PAKISTAN', u'KARACHI (PAKISTAN)', u'SUPPLEMENTARY PLUMPY', 0)
When I iterate over the list without sorting as follows:
for tuple in data:
if tuple[2] == "SUPPLEMENTARY PLUMPY":
print tuple
only 1 tuple is printed:
(u'INDIA', u'MUMBAI (INDIA)', u'SUPPLEMENTARY PLUMPY', 0)
When I iterate over the list while sorting as follows:
for tuple in sorted(data):
if tuple[2] == "SUPPLEMENTARY PLUMPY":
print tuple
All 3 tuples are printed!
Of the 98 unique values, 94 are iterated over when I don't sort the list, and all 98 are covered if I iterate over the sorted list. It's driving me crazy.
I tried replicating the behaviour in a minimum working example, but there the issue doesn't appear... The code where the issue does appear is massive and sadly can't be shared, so I made my description as detailed as I can in the hope of sparking some ideas!
Can you guys help me figure this one out? Any guesses as to why this is happening?
Thank you in advance, Koen
Upvotes: 0
Views: 59
Reputation: 536567
Since you haven't posted the actual code where the problem is, there's very little we can do beyond idle, ignorant speculation.
My idle, ignorant speculation is this: you're altering the list somewhere in code you haven't shown us, at the same time as iterating it. By adding sorted()
around the list you are effectively making a copy of the list, so only the original list is being altered as you go, not the copy you are iterating.
Upvotes: 1