Quote:
Originally Posted by Xhad
That's called a list comprehension. In this case it's just copying the list. The equivalent as a for would be:
Code:
self.viruses = []
for x in newViruses:
self.viruses.append(x)
The main advantage is code length and readability once you understand it; see my response to this post
List comprehensions are also faster (and in some cases, much faster). Python is a slow language, and when you write out a for loop python actually has to continually run over the loop to execute it, which is slow. List comprehensions, since they encapsulate the operation you are trying to do more comprehensively, allow python to optimize the execution.
For example in the below code, I'm manually copying a list with 1000 items and then doing the same operation with a list comprehension. The list comprehension is about 2.5x faster to do the exact same operation.
Code:
import timeit
things = [0] * 1000
def manual_copy():
copy = []
for thing in things:
copy.append(thing)
def list_comprehension():
copy = [thing for thing in things]
t = timeit.Timer('manual_copy()', 'from __main__ import manual_copy')
print 'Manual copy:', t.timeit(number=100000)
t = timeit.Timer(
'list_comprehension()', 'from __main__ import list_comprehension')
print 'List comprehension:', t.timeit(number=100000)
Output (time in seconds, lower is faster):
Code:
Manual copy: 16.9621839523
List comprehension: 6.79605603218