pUTa432
pUTa432

Reputation: 57

Join function with broken for loop in python

Why does this work:

"".join(str(i) for i in range(10))

and this does not?

for i in range(10):
...     "".join(str(i))

I want the the second one to output the same string of 1-9 digits. I am new to python.

Upvotes: 2

Views: 680

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140266

str.join expects an iterable, which you're providing in both cases.

In the first case, the generator comprehension provides the digits to the same join function and you get your expected result.

In the second case, join iterates on the characters of a digit as string, and rebuilds it identical (so join is useless here):

"".join(str(i)) is the same as str(i)

And since you're supposedly printing those expressions you end up adding a newline in between each digit. In your loop you would need print(i,end="") (python 3)

As a side note

"".join([str(i) for i in range(10)])

is slightly more performant than just

"".join(str(i) for i in range(10))

because join needs to build a list anyway to allocate the destination string. Passing a list directly speeds up the process.

Upvotes: 2

Related Questions