lauro199471
lauro199471

Reputation: 19

Python 3.5 For loop Set return method

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

Upvotes: 1

Views: 161

Answers (1)

jpp
jpp

Reputation: 164613

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

Upvotes: 0

Related Questions