Reputation: 561
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?
Upvotes: 0
Views: 71
Reputation: 27802
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.
Upvotes: 1