List comprehension without [ ] in Python
list-comprehension, python
Solution
>>>''.join( str(_) for _ in xrange(10) )
This is called a generator expression, and is explained in PEP 289.
The main difference between generator expressions and list comprehensions is that the former don't create the list in memory.
Note that there's a third way to write the expression:
''.join(map(str, xrange(10)))
Problem
Joining a list: ``` >>> ''.join([ str(_) for _ in xrange(10) ]) '0123456789' ``` `join` must take an iterable. Apparently, `join`'s argument is `[ str(_) for _ in xrange(10) ]`, and it's a list comprehension. Look at this: ``` >>>''.join( str(_) for _ in xrange(10) ) '0123456789' ``` Now, `join`'s argument is just `str(_) for _ in xrange(10)`, no `[]`, but the result is the same. Why? Does `str(_) for _ in xrange(10)` also produce a list or an iterable?