kharandziuk
kharandziuk

Reputation: 12920

How to find indexes of string in lists which starts with some substring?

I have some list like this:

lines = [
    "line",
    "subline2",
    "subline4",
    "line",
]

And I want to take list of index of lines which starts with some substring.

I use this approach:

starts = [n for n, l in enumerate(lines) if l.startswith('sub')]

but maybe anybody knows more beautiful approach?

Upvotes: 15

Views: 15471

Answers (2)

Dirk Herrmann
Dirk Herrmann

Reputation: 5949

While I like your approach, here is another one that handles identical entries in lines correctly (i.e. similar to the way your sample code does), and has comparable performance, also for the case that the length of lines grows:

starts = [i for i in range(len(lines)) if lines[i].startswith('sub')]

Upvotes: 3

sacuL
sacuL

Reputation: 51425

I know it's been a while since this question was active, but here's another solution anyways in case anyone is interested.

Your way seems fine, but here is a similar strategy, using the list.index() method:

starts = [lines.index(l) for l in lines if l.startswith('sub')]

As far as time goes, the two functions clock in at about the same (on average 1.7145156860351563e-06 seconds for your enumerate solution and 1.7133951187133788e-06 seconds for my .index() solution)

Upvotes: 8

Related Questions