Replace for loop with list comprehension

By : TheFoxx
Source: Stackoverflow.com
Question!
string = ""
for e in list:
    string += e

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

By : TheFoxx


Answers
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.

By : spatz


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.



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


This video can help you solving your question :)
By: admin