user3151828
user3151828

Reputation: 363

Get string of certain length out of a list

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

Answers (3)

arshajii
arshajii

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 Nones 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

Ben
Ben

Reputation: 2472

filter(lambda s: len(s) == 3, list1)

Upvotes: 1

aruisdante
aruisdante

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

Related Questions