Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "()" and "[]" when generating in Python?

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.

like image 439
zfz Avatar asked Nov 21 '12 10:11

zfz


3 Answers

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)))
like image 97
NPE Avatar answered Nov 09 '22 16:11

NPE


The syntax for a tuple is not parentheses (), it's the comma ,. You can create a tuple without parentheses:

x = 1, 2, 3

If you want to create a tuple from a comprehension, just use the tuple constructor:

tuple(tuple((a,b) for a in nodes )for b in nodes)
like image 33
ecatmur Avatar answered Nov 09 '22 16:11

ecatmur


Because the syntax (x for x in l) is a so called "generator expression": see http://docs.python.org/2/reference/expressions.html#generator-expressions

like image 40
Jonathan Ballet Avatar answered Nov 09 '22 18:11

Jonathan Ballet