TheFoxx
TheFoxx

Reputation: 1693

Replace for loop with list comprehension

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

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

Upvotes: 1

Views: 1026

Answers (3)

rankthefirst
rankthefirst

Reputation: 1468

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

Upvotes: 1

Peter Collingridge
Peter Collingridge

Reputation: 10979

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.

Upvotes: 3

drrlvn
drrlvn

Reputation: 8437

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.

Upvotes: 13

Related Questions