[Python-ideas] List Comprehensions

Steven D'Aprano steve at pearwood.info
Wed Feb 3 06:04:03 EST 2016


On Wed, Feb 03, 2016 at 02:04:53PM +0530, shiva prasanth wrote:

> In [4]: z=[x for x in range(10),100]  # should be [ 0 , 1, 2, 3, 4, 5, 6,
> 7, 8, 9, 100]
> 
> # but  output is not as expected
> # following is the output
> # other wise it should show error
> In [5]: z
> Out[5]: [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 100]


Your suggestion is not how iteration works in Python:

py> for x in range(10), 100:
...     print x
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
100


To get the result you want, you need to do this:

# Python 2
py> [x for x in range(10) + [100]]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]

# Python 3
py> from itertools import chain
py> [x for x in chain(range(10), [100])]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]


I've sometimes thought that Python should have a iterator concatenation 
operator (perhaps &) which we could use:

[x for x in range(5) & [100] & "spam"]
=> returns [0, 1, 2, 3, 4, 100, 's', 'p', 'a', 'm']



-- 
Steve


More information about the Python-ideas mailing list