Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function repeatedly until a condition is met and collect the results in a list, in a single statement without a while loop

I am making a programme and I have this line of code:

self.languages = [while ans != 'no': ans = input('Insert a language you know: ')]

I hope to achieve this interaction:

Insert a language you know: English
Insert a language you know: French
Insert a language you know: no

and then self.languages will be ['English', 'French'].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But when I execute it this is the output:

self.languages = [while ans != 'no': ans = input('Insert a language you know: ')]
                 ^^^^^
SyntaxError: invalid syntax

I also tried this:

self.languages = while ans != 'no': ans = input('Insert a language you know: ')

but it gives the same error.

What can I do?

>Solution :

There is no syntax similar to list comprehensions that uses while instead of for.

However, you can use iter in its two-argument form:

  • The first argument is a callable f that is executed repeatedly.

  • The second argument is a sentinel value that stops the iteration if f returns it.

  • The results of the iteration (the return values of f before the sentinel) are collected using the list() constructor.

list(iter(lambda: input('Insert a language you know: '), 'no'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading