1

I have a list:

foolist = ['123-asd', '234-asd', '345-asd']

I want to find the index of the string that contains '234'. At the moment I have this:

boollist = ['234' in i for i in foolist]

which would produce a list of True and Falses for each index for foolist.

Then to find the index, [print(i) for i,j in enumerate(foolist) if j==True]

This seems abit unecessary, does anyone have a more eloquent method of finding the index of a string in list based on a part of that string

2
  • 2
    [i for i,j in enumerate(foolist) if '234' in j] ? Commented Aug 23, 2018 at 11:09
  • 1
    Yeah that worked, thanks for that, Cheerws Commented Aug 23, 2018 at 11:11

1 Answer 1

3

You can use next with a generator expression and split by a specific character to reflect the structure of your strings:

foolist = ['123-asd','234-asd','345-asd']

res = next(i for i, j in enumerate(foolist) if '123' in j.split('-')[0])  # 0

If there can be multiple matches, you can use a list comprehension:

res = [i for i, j in enumerate(foolist) if '123' in j.split('-')[0]]  # [0]

For equality, you should use j.split('-')[0]] == '123' as your condition instead.

Note on print within a comprehension

It's good practice to avoid print in a list comprehension, as it will return None. You will notice that, while your terminal will print the indices it finds, you are also building a list of None items with length equal to the number of matches. For all intents, that list has no use.

If you are only interested in printing items, you can use a for loop with a generator expression:

for idx in (i for i, j in enumerate(foolist) if '123' in j.split('-')[0]):
    print(idx)
Sign up to request clarification or add additional context in comments.

4 Comments

"...as it will return None" While I agree, I think that's not the reason. It may be perfectly fine to call functions returning None in a list comprehension, the bad-practice bit is using the list comprehension for side-effects and discarding the result.
@tobias_k, Thanks, that's what I meant, but you've described it more eloquently. I'll update with a bit more :)
stackoverflow.com/questions/51984323/… is more concise, more general, and solves the task "I want to find the index of the string that contains '234'. ". Too bad it isn't a votable answer. This is also fine, though, for this example.
@ChristophTerasa, Have to be pedantic here, it really matters where you put the bold: "the index of the string that contains '234'". This implies there's only one string. In my opinion, a scalar is a better object type for a single item than a list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.