1

I'm running the following code:

if course_name.lower() in [x.split('.')[0].lower() for x in user_courses]:
    do_code()

When the do_code() block runs, I know that course_name.lower() was matched in the list. Is there any way of getting the value of x in the list that course_name.lower() matched? As you can see, since I'm taking the [0] index when creating the list in

[x.split('.')[0].lower() for x in user_courses]

I want the entire value of user_courses that it matches, not just the zero indexed which is what course_name.lower() contains.

Thanks!

2 Answers 2

5

You could do it by going the other way around:

lower_name = course_name.lower()
matches = [x for x in user_courses if x.split('.')[0].lower() == lower_name]
if matches:
    match = matches[0]
    # match is the matched name

That is, filter your list comprehension based on equality with course_name.lower(). If there is anything left in the list, then it will equal course_name.lower(). (There could in theory be multiple items left in the list, but if so they're all equal, so we can just take the first one.)

I pulled the calculation of course_name.lower() out of the list comprehension to avoid recomputing it repeatedly.

0
1

list.index is built for this. How about this?

wordList = [x.split('.')[0].lower() for x in user_courses]
try:
    wordIndex = wordList.index(course_name.lower())
except ValueError:
    do what you will

Not the answer you're looking for? Browse other questions tagged or ask your own question.