Cameron
Cameron

Reputation: 258

Python: Elegant way to return multiple values in a while loop

I'm pretty much just doing this...

while not something():
    pass

But I want the function something() to return another value other than True or False, specifically a list. In C I'd just return it by plugging in a reference as a parameter but Python doesn't seem to like doing things that way. Therefore in the something() function I would obviously just return 2 values. I'm ok with that. The issue I have is that the code with the while loop doesn't look elegant and so I presume there must be a better way.

In C:

int a[2];
while(!something(a)); //presume that 'a' updates and the loop breaks

In Python:

bool_value, a = something()
while not bool_value:
    bool_value, a = something()

I know it's not such a big deal but just the fact that I have to write the same line twice seems a bit bad. Is there some sort of syntax I can use to call the function and return the 'a' all within the while line?

Upvotes: 3

Views: 1845

Answers (2)

chthonicdaemon
chthonicdaemon

Reputation: 19830

The answer by user2393267 is the idiomatic way of doing do..while kind of structure in Python. You can, however, follow exactly the same pattern as you have in your question for the list case:

a = [1, 2, 3]
while not something(a):
    pass

It's just not very Pythonic, but it will actually work and allow you to modify a.

Upvotes: 0

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

while True:
    bool_value, a = something()
    if not bool_value:
       break

Upvotes: 3

Related Questions