1

we can use set.iterator().remove() in 'for' loops in java. By contrast, how to write similar python code?

def fun1():
    a=set(range(10))
    for num in a:
        if(num%2==0):
            a.remove(num)
    print(a)

def fun2():
    a=range(10)
    for num in a:
        if(num%2==0):
            a.remove(num)
    print(a)

#RuntimeError: Set changed size during iteration
fun1()

#works well
fun2()
yichudu
  • 165
  • 2
  • 12
  • Add another list argument maybe? `list(set(range(10)))` for the first function then change it back later. Or you can make a copy of the set and iterate using that. – Taku Mar 27 '17 at 01:59
  • 1
    As mentioned, you can make a copy `for num in tuple(a):` – tdelaney Mar 27 '17 at 02:02
  • There's a discussion about how to do it for list: http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating, for set it should be similiar – shizhz Mar 27 '17 at 02:20
  • @tdelaney `tuple(a)` or `list(a)` seems occupies a new memory space to store the set's elements, which is unnecessary when the set is big. – yichudu Mar 27 '17 at 02:38
  • @yichudu but the accepted answer does nearly the same thing. Its a bit smaller because you filter out elements but two sets occupy memory at the point the function returns. The difference is my solution modifies the existing set and the accepted answer creates a new one. I don't know which is more important in your case, but my example more closely matches the java example. – tdelaney Mar 27 '17 at 02:46
  • @tdelaney Thanks for your answer. As you say, the accepted answer is smaller because it filters some out. I think python's iterator is weaker than java. It lacks even `iterator.hasNext()` method. – yichudu Mar 27 '17 at 03:04

1 Answers1

2

This should work:

def fun3():
    a = set(range(10))
    return set(num for num in a if num % 2)

print(fun3())

The answer uses a generator expression, num for num in a if num % 2, to filter the members of a.

Tom Lynch
  • 893
  • 6
  • 13
  • This is great but it should be noted that it does not modify the set in place. That's not bad... but is different than the java sample. – tdelaney Mar 27 '17 at 02:47