0

How may I access to a tuple initialized within a if/else statement without using tuple() and list() functions?

I have this code:

if x > y:
    foo = (a, b)
elif y > x:
    foo = (b, a)

(tmp1, tmp2) = foo

but python returns: UnboundLocalError: local variable 'foo' referenced before assignment.

In other programming languages you can initialize the variable outside the statement, but what about this case?

Important: I need to work with a tuple, not a list.

Update: I don't need the case x == y, so I've changed my code adding a further condition:

foo = None
if x > y:
    foo = (a, b)
elif y > x:
    foo = (b, a)

if foo != None:
    (tmp1, tmp2) = foo

Update2: Or, similarly:

if x > y:
    foo = (a, b)
elif y > x:
    foo = (b, a)
else:
    foo = ()

if len(foo) > 0:
    (tmp1, tmp2) = foo

3 Answers 3

2

Python does not have block scope. And the tuple and list functions are irrelevant here, as is the choice of which type you use.

The only reason foo would be undefined here is because you have forgotten a condition: when x and y are equal.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I know, but I don't need that condition. Anyway, I've solved adding a futher condition: if edge != None: .... Thank you.
1

That should work, but try explicitly declaring foo before the if-else block

x=3
y=2
a=1
b=2
foo=None #tell python foo must be reserved at this scope level
if x > y:
    foo = (a, b)
elif y > x:
    foo = (b, a)
elif y == x: #need to remember this case
    foo = (b, a)

(tmp1, tmp2) = foo

Comments

1

In a single line, assuming you forgot the case x == y in your code:

(tmp1, tmp2) = (a, b) if x > y else (b, a)

But if you want to keep your syntax, just do not forgot the == condition!

if x > y:
    foo = (a, b)
else:
    foo = (b, a)

(tmp1, tmp2) = foo

(edited after @Daniel Roseman's answer)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.