string = ""
for e in list:
string += e
How would this for loop be expressed as a list comprehension so that it outputs a string?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The preferred idiom for what you want is:
Explained:
join()is a string method that gets an iterable and returns a string with all elements in the iterable separated by the string it is called on. So, for example,', '.join(['a', 'b'])would simply return the string'a, b'. Since lists are iterables, we can pass them tojoinwith the separator''(empty string) to concatenate all items in the list.Note: since
listis the built-in type name for lists in Python, it’s preferable not to mask it by naming a variable ‘list’. Therefore, I’ve named the list in the examplel.