Reputation: 53
I want to find a particular element in a list like this:
my_list.find { |e| e == 'find this' }
I know in Python I can do:
[e for e in my_list if e == 'find this']
But this returns a list as opposed to the element I want.
I know how I can do this by iterating through the list, but I want to know if there's a more concise way of doing it.
Upvotes: 0
Views: 73
Reputation: 188134
You could use list.index, which
returns the index in the list of the first item whose value is x. It is an error if there is no such item.
>>> l = ["1", "se", "uz", "tz", "find this", "that"]
>>> l.index("find this")
4
>>> l[l.index("find this")]
'find this'
>>> l[l.index("find that")]
...
ValueError: 'find that' is not in list
If all your app does is searching for exact keys, you could also use a dictionary (called Hash in Ruby, I guess) instead - to reduce lookup times from O(n) to amortized O(1).
Upvotes: 0
Reputation: 1124110
You can find the first matching element with a generator expression and next()
:
match = next((e for e in my_list if e == 'find this'), None)
This sets match
to None
if no elements matched.
Because a generator expression is used, only enough elements in my_list
are inspected to find the first match, after which the search is stopped.
The sample search you gave is rather pointless, of course, as you are basically using simple equality. For more complex attribute searches it makes more sense.
Upvotes: 2