bernie2436
bernie2436

Reputation: 23931

Bad syntax in python list comprehension

I have a list of xlib elements like this:

<Choice ID="91149" Total="21"/>
<Choice ID="91139" Total="14"/>
<Choice ID="91159" Total="58"/>

I want to pick the element with ID = 91149. In .NET, I could do something like

element91149 = (from p in choices where p.id=91149).first

I am trying at the syntax in python, working from this example from the python tutorial...

#example from documentation = x for x in 'abracadabra' if x not in 'abc'

My implementation:

h = x for x in results if x.get("ID")=="91149" #invalid syntax

What am I doing wrong?

Upvotes: 0

Views: 316

Answers (1)

user2555451
user2555451

Reputation:

List comprehensions must be enclosed by square brackets [...]:

h = [x for x in results if x.get("ID")=="91149"]

Just for the record, using normal parenthesis (...) will create a generator expression:

h = (x for x in results if x.get("ID")=="91149")

However, as @Ashwini mentioned, it is generally very inefficient to read a whole list into memory when all you want is the first item that meets a condition.

Instead, it is usually much faster to use next and a generator expression:

h = next(x for x in results if x.get("ID")=="91149")

Unlike the list comp. (which does it all at once), this solution will yield the items one at a time. Moreover, it will stop once it finds an item that meets the condition.

Be warned though that it will also raise a StopIteration error if it cannot find the item. To avoid this, you can give next a default value to return:

h = next((x for x in results if x.get("ID")=="91149"), None)

In this case, h will be assigned to None if an item that meets the condition cannot be found.

Upvotes: 7

Related Questions