1

Why do I have to enclose the following code in brackets? Why is there a difference between square and round brackets?

>>> a= [1,2,3]
>>> (str(x) for x in a)
<generator object <genexpr> at 0x10ade8af0>
>>> [str(x) for x in a]
['1', '2', '3']
Megatron
  • 15,909
  • 12
  • 89
  • 97
  • 4
    `()` makes a generator, `[]` a list. – Aleph Oct 23 '13 at 14:22
  • 3
    Isn't the output clear enough? The first one is a generator expression. Just search for this term, you will sure get lot of questions talking about this. – Rohit Jain Oct 23 '13 at 14:22
  • 1
    Python doesn't use casting. Some types support creating a new instance using an object of a different type (l = list("foo"), e.g.), but that is different from treating an object of type A as if it were an object of type B. – chepner Oct 23 '13 at 14:41

1 Answers1

4

(str(x) for x in a) is a generator expression

[str(x) for x in a] is a list comprehension.

Brionius
  • 13,858
  • 3
  • 38
  • 49
  • 1
    Here's a [discussion of the differences](http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension), from the archives. – hunse Oct 23 '13 at 15:17