1
string = ""
for e in list:
    string += e

How would this for loop be expressed as a list comprehension so that it outputs a string?

0

3 Answers 3

13

The preferred idiom for what you want is:

string = ''.join(l)

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 to join with the separator '' (empty string) to concatenate all items in the list.

Note: since list is 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 example l.

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

Comments

3

List comprehensions return lists not strings. Use join()

string = "".join(lst)

To understand the join method more fully, see: http://docs.python.org/library/stdtypes.html#str.join

Also, beware of naming a variable as list since it is a recognized type and will cause trouble down the line.

Comments

1

not a list comprehension, but still short, hope works.

string = ''
list = ['a',' f' , 'f' ,'daf','fd']

x =reduce(lambda x,y: x + y, list, string)
print x

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.