En Fri, 15 May 2009 22:17:43 -0300, Sam Tregar <s...@tregar.com> escribió:

Hello all.  Can anyone explain why this creates a list containing a
dictionary:

  [{'a': 'b', 'foo': 'bar'}]

But this creates a list of keys of the dictionary:

  list({ "a": "b", "foo": "bar" })

I expected them to be equivalent but clearly they're not! I'm using Python
2.6.1 if that helps.

First, a list display [...] and the list constructor list(...) aren't quite the same: [1,2,3] is ok; list(1,2,3) is an error. So clearly they are not equivalent and you'll have to tune up your expectations :)

list() can take a *single* argument only, a list display [a, b, c] can have many comma-separated expressions. So the only possible confusion is between list(<x>) and [<x>] where <x> stands for a single expression.

In list(<x>), <x> must be iterable, and means (more or less):

result = []
for item in <x>:
  result.append(item)
return result

In words, list(<x>) iterates over its argument, collecting each item yielded into the returned list.

For example, a dictionary is iterable, yielding its keys; list(some_dictionary) behaves like you describe in your example. Another one: list("abc") returns ['a', 'b', 'c'] because a string is iterable too, yielding each of its characters. list(3) is an error because its argument must be iterable; list([3]) works, but it's a silly way of simply writting [3].

On the other hand, a list display like [...] just collects the expressions inside the brackets into a list. No iteration is involved: [<x>] builds a list containing a single element, and it doesn't matter whether <x> is iterable or not: whatever it is, it becomes the first and only element in the returned list.

There is another way of building a list, a "list comprehension". The syntax uses brackets too, but explicitely involves an iteration with the "for" keyword:
[x for x in range(10) if x%3!=0] yields [1, 2, 4, 5, 7, 8]

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to