lookster123
lookster123

Reputation: 19

String join() method used with for loop

I need your help, because I don't understand why is possible to use the join() method with a forloop as an argument.

Ex:

" ".join(str(x) for x in list)

Python Documentation:

str.join(iterable) Return a string which is the concatenation of the strings in iterable.

A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

Can please somebody explain?

Upvotes: 2

Views: 6733

Answers (1)

James
James

Reputation: 2721

The statement (str(x) for x in list) is called a generator expression:

>>> (str(x) for x in [1,2,3])
<generator object <genexpr> at 0x7fc916f01d20>

What this does is create an object that can be iterated over exactly once, and yields elements that would be created one at a time. You can iterate over it as you would a list, like this:

>>> gen = (str(x) for x in [1,2,3])
>>> for s in gen:
...     print s
... 
1
2
3

A generator expression is iterable, so what the join function does is iterate over it and join its values.

Upvotes: 5

Related Questions