1

I do not understand what these lines are doing.

S = {-4 , 4 ,-3 , 3, -2 , 2, -1, 1, 0};
{x for x in S if x >= 0}

I know S is a set. I know we are looping through set S but what I don't understand is what is the "x" doing before the for loop? And when I use the print in the function I get error saying:

NameError: name 'x' is not defined
bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • 1
    The scope of the loop variable `x` is the set comprehension itself (everything from `{` to `}`). It does not exist outside of the braces. – DYZ Feb 04 '18 at 00:01
  • `x` is the throwaway variable defined within the scope of the set-comprehension in order to carry the value of the set's items that satisfied the condition. You can not use that variable outside the comprehension scope. – Mazdak Feb 04 '18 at 00:02
  • 1
    This is a set comprehension. It's just a compact way of defining sets. You can read more about comprehensions [here](http://www.secnetix.de/olli/Python/list_comprehensions.hawk). There are comprehensions for defining new lists, sets, dictionaries, and generators. – Patrick Haugh Feb 04 '18 at 00:03
  • @LauroCabral, did the below response solve your problem? if so, feel free to accept - or comment further. – jpp Feb 04 '18 at 18:50

1 Answers1

0

Since you are familiar with another programming language, here are three ways of processing your algorithm.

result via set comprehension, where x is scoped only to the comprehension. Considered most pythonic and usually most efficient.

result_functional, functional equivalent of result, but less optimised than set comprehension implementation when lambda is used. Here x is scoped to the anonymous lambda function.

result_build, full-blown loop, usually least efficient.

S = {-4 , 4 ,-3 , 3, -2 , 2, -1, 1, 0}

result = {x for x in S if x >= 0}
# {0, 1, 2, 3, 4}

result_functional = set(filter(lambda x: x >= 0, S))
# {0, 1, 2, 3, 4}

result_build = set()

for x in S:
    if x>= 0:
        result_build.add(x)
        print(x)

# 0
# 1
# 2
# 3
# 4     

assert result == result_build
assert result == result_functional
jpp
  • 159,742
  • 34
  • 281
  • 339