[Tutor] Appropriate use of list comprehension
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Jun 10 08:26:50 EDT 2020
On 10/06/2020 09:32, Manprit Singh wrote:
> I just need to know that the way I have used to enter 3 names inside the
> list , entered through keyboard, using list comprehension is syntactically
> correct or not .
The best check for syntax is the Python interpreter. if its happy then
the syntax is fine. You can try pylint and similar tools for more
critical analysis.
> Is there any other more efficient way to do this?
> Below is the code given :
>
> val = [input("enter name") for _ in range(3)]
Not more efficient no, but for production code you should wrap it
in a try/except block and usually, when reading user input in real
code, we need at least minimal data sanity checks. But you can
wrap that in a function and use the function in the comprehension.
It is a valid use of a comprehension if that's what you are asking.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list