Reputation: 363
What I am after is like this:
list1 = ["well", "455", "antifederalist", "mooooooo"]
Something that pulls "455"
from the list because of the number of characters.
Upvotes: 3
Views: 1342
Reputation: 129572
You can use next()
with a generator:
>>> list1 = ["well", "455", "antifederalist", "mooooooo"]
>>>
>>> next(s for s in list1 if len(s) == 3)
'455'
next()
also lets you specify a "default" value to be returned if the list doesn't contain any string of length 3. For instance, to return None
in such a case:
>>> list1 = ["well", "antifederalist", "mooooooo"]
>>>
>>> print next((s for s in list1 if len(s) == 3), None)
None
(I used an explicit print
because None
s don't print by default in interactive mode.)
If you want all strings of length 3, you can easily turn the approach above into a list comprehension:
>>> [s for s in list1 if len(s) == 3]
['455']
Upvotes: 5
Reputation: 9115
And if you're looking to pull all items out of the list greater than some length:
list2 = [string for string in list1 if len(string) >= num_chars]
Upvotes: 0