0

During learning Django framework basics I found the following piece of code. I know how does join() method work but frankly speaking I have no idea what's inside.

output = ', '.join([p.question for p in latest_poll_list])

Of course the result is very clear to me, but I would rather use it this way

array = []
for p in latest_poll_list:
    array.append(p.question)
output = ', '.join(array)

Can anyone explain?

Robin92
  • 413
  • 1
  • 6
  • 19
  • 1
    its called a `list comprehension` and it is very important in python ... I would suggest learning about them – Joran Beasley Jul 31 '13 at 15:22
  • 1
    List comprehension is quite good, although sometimes it is difficult to see what they do in one go, especially if they are mixed within other functions or statements. – Jblasco Jul 31 '13 at 15:24
  • 1
    http://www.pythonforbeginners.com/lists/list-comprehensions-in-python/ has a good explanation of list comprehensions. – Annika Peterson Jul 31 '13 at 15:24

1 Answers1

1
array = [p.question for p in latest_poll_list]

is a list comprehension. It is equivalent to:

array = []
for p in latest_poll_list:
    array.append(p.question)

So the code you posted will do exactly the same thing. A list comprehension is just a more compact way of creating a list with a for loop.


FYI, you don't really need to create a list,

output = ', '.join(p.question for p in latest_poll_list)

should also work, since join takes in an iterable.

jh314
  • 24,533
  • 14
  • 58
  • 79
  • 2
    Even better: drop the brackets. You'll get a generator expression, which has all the awesome of a list comprehension without even building a list. – user2357112 supports Monica Jul 31 '13 at 15:26
  • 1
    `join()` works better with a list over a generator expression. – Sukrit Kalra Jul 31 '13 at 15:27
  • @SukritKalra The implementation os `str.join` specifically is slightly faster, yes, but in general avoiding the list can be desirable and even if it was slower it'd be preferable as it has less clutter and is prettier. –  Jul 31 '13 at 15:28
  • @jh314 Im not sure thats exactly true(equivelency) ... use dis.dis to inspect the stuff actually under the hood :P – Joran Beasley Jul 31 '13 at 15:29