What's the difference between "()" and "[]" when generating in Python?
generator, list, python, tuples
Solution
The fundamental difference is that the first is a generator expression, and the second is a list comprehension. The former only yields elements as they are required, whereas the latter always produces the entire list when the comprehension is run.
For more info, see Generator Expressions vs. List Comprehension
There is no such thing as a "tuple comprehension" in Python, which is what you seem to be expecting from the first syntax.
If you wish to turn `tour1` into a tuple of tuples, you could use the following:
In [89]: tour1 = tuple(tuple((a,b) for a in nodes )for b in nodes)
In [90]: tour1
Out[90]:
(((20, 20), (21, 20), (22, 20), (23, 20), (24, 20), (25, 20)),
((20, 21), (21, 21), (22, 21), (23, 21), (24, 21), (25, 21)),
((20, 22), (21, 22), (22, 22), (23, 22), (24, 22), (25, 22)),
((20, 23), (21, 23), (22, 23), (23, 23), (24, 23), (25, 23)),
((20, 24), (21, 24), (22, 24), (23, 24), (24, 24), (25, 24)),
((20, 25), (21, 25), (22, 25), (23, 25), (24, 25), (25, 25)))
Problem
There is a list: nodes = [20, 21, 22, 23, 24, 25]. I used two ways to generate new 2-dimentional objects: ``` tour1 = (((a,b) for a in nodes )for b in nodes) tour2 = [[(a,b) for a in nodes ]for b in nodes] ``` The type of tour1 is a generator while tour2 is a list: ``` In [34]: type(tour1) Out[34]: <type 'generator'> In [35]: type(tour2) Out[35]: <type 'list'> ``` I want to know why tour1 is not a tuple? Thanks.