Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - list comprehension without assignment

Today I was parsing a directory index with a list of paths to zip files using BeautifulSoup and came across an interesting thing. Let's assume I would like to take all the href properties of the tags I got and put them directly into a Queue:

q = Queue.Queue()
[q.put(tag['href']) for tag in soup.findAll('a')]

I've never run into a situation like this before where a comprehension could be used inline without assigning it to anything, just to generated another iterator through some routine call. Is this considered bad practice? Is it "pythonic", per se? Was there a better one-liner to put all the items into the queue?

like image 251
DeaconDesperado Avatar asked Jan 10 '13 01:01

DeaconDesperado


People also ask

Can you do list comprehension in Python?

Python is famous for allowing you to write code that's elegant, easy to write, and almost as easy to read as plain English. One of the language's most distinctive features is the list comprehension, which you can use to create powerful functionality within a single line of code.

Can you do assignment in list comprehension?

We can also use assignment expressions in list comprehensions.

Is Python list comprehension fast?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations. Below, the same operation is performed by list comprehension and by for loop.

Can you do list comprehension with strings?

List comprehension works with string lists also. The following creates a new list of strings that contains 'a'. Above, the expression if 'a' in s returns True if an element contains a character 'a'. So, the new list will include names that contain 'a'.


1 Answers

There are many opinions on this thread, I can only speak from coding conventions at my organization.

there are many ways to affect a loop, but a key attribute of list comprehensions is that they create lists, with one item for each in the iterated over sequence.

>>> import Queue
>>> q = Queue.Queue()
>>> [q.put(item) for item in range(5)]
[None, None, None, None, None]
>>>

this unused list is obviously wasteful. As such, this construction, a list comprehension with unused return value; is forbidden from appearing in our code base. An explicit loop like above, or a generated combined with something that consumes it, for instance:

>>> any(q.put(item) for item in xrange(5))
False
>>>

or just:

>>> for item in xrange(5):
...     q.put(item)
...
>>>

is required to pass review.

like image 153
SingleNegationElimination Avatar answered Sep 21 '22 14:09

SingleNegationElimination