0

Playing around with python3 REPL and noticed the following:

Why are print( [zip([1,2,3], [3,1,4])] ) and print( list(zip([1,2,3], [3,1,4])) ) different?

The first returns [<zip object at 0xblah>] and the second returns [(1,3), (2,1), (3,4)].

Trying to understand why the list comprehension in the first statement doesn’t give me the result that the list() constructor gives - I think I'm confused about the difference between list comprehension and list() and would appreciate insight into what's happening under the hood.

Searching gives me this question on lists and tuples which doesn't answer my question.

Edit: A suggested question on The zip() function in Python 3 is very helpful background, but does not address the confusion in my question about the difference between a list comprehension and a list literal, so i prefer the submitted answer below as more complete.

phoenixdown
  • 828
  • 1
  • 10
  • 16
  • Does this answer your question? [The zip() function in Python 3](https://stackoverflow.com/questions/31683959/the-zip-function-in-python-3) – Red Jun 08 '20 at 20:59
  • 1
    `[zip([1,2,3], [3,1,4])]` *is not a list comprehension*. That is a list literal with a single element, the value you get by evaluating the expression `zip([1,2,3], [3,1,4])` which of course is a `zip` object – juanpa.arrivillaga Jun 08 '20 at 21:00
  • 3
    `[x]` simply means "a list containing x", whereas `list(x)` means "a list containing the elements of x". They are not interchangeable (and neither of them is a list comprehension). – khelwood Jun 08 '20 at 21:00
  • 1
    The equivalent of ``list(x)`` is ``[*x]``, not ``[x]``. Try ``[*zip([1,2,3], [3,1,4])]``. – MisterMiyagi Jun 08 '20 at 21:10
  • thanks @MisterMiyagi - is `[*x]` considered a "list comprehension"? trying to understand what the `*` does - is it shorthand for a list comprehension or does it call the list constructor `list()`? – phoenixdown Jun 08 '20 at 21:14
  • 2
    `[*x]` is not a list comprehension. It's a list containing `*x`, which means "unpack the items of `x`". `[*x]` will give you the same outcome as `list(x)`. A list comprehension always incorporates the words `for` and `in`. – khelwood Jun 09 '20 at 11:31

1 Answers1

3

The first statement is not a list comprehension, a list comprehension would give you the same result. It is just a list literal containing a zip object:

This would be a list comprehension:

[value for value in zip([1,2,3], [3,1,4])]

The above will print the same as list(zip([1, 2, 3], [3, 1, 4])).


In general, [something] means: A list with one element: something.

On the other hand, list(something) means: Iterate over the values in something, and make a list from the result. You can see the difference for example by putting primitive objects inside it, like a number:

>>> [2]
[2]
>>> list(2)
TypeError: 'int' object is not iterable
L3viathan
  • 26,748
  • 2
  • 58
  • 81