I have a generator:
foundUnique = set()
def unique_items(myList, index, clearFlag):
for item in myList:
if clearFlag is True:
foundUnique.clear()
clearFlag = False
if item[index] not in foundUnique:
yield item
foundUnique.add(item[index])
And I am using this `unique_items to get a unique list:
senderDupSend = unique_items(ip, 4, True)
Now I want my set to be reachable (I can print its element or do some changes on specific element …..) but when I write:
for item in foundUnique:
print item
It prints nothing!
But if I write:
for item in senderDupSend:
print item
for item in foundUnique:
print item
It prints all foundUnique items.
Please tell what did I do wrong? How can I solve this problem?
The problem is that
unique_itemsis a generator so thatis a generator that needs to be iterated over. When you run
the generator has not actually run yet so
foundUniqueis still empty.When you later go on to do
It should print out the set twice: once while it is being constructed and once after it is constructed.
It seems like what you are trying to do is construct a set that has the same index taken from every element of some sequence. You can do it like this very easily:
In the concrete case that you show, it would be:
If you later wanted to extend the set to contain other items, you could do