I know there have been a lot of questions regarding list comprehensions, but I can't seem to find one that fits my question.
I want to return the index of just one specific character in a list of strings.
char_list = ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
def get_index(c, char_list):
return [index for index in range(len(char_list)) if c == char_list[index]]
get_index('r', char_list)
# This returns [9] which is what I want.
This previous list comprehension works to do that, but I want to write an else statement in it to return [-1] if the string passed in isn't present in the list.
I've looked at this question (if else in a list comprehension) and it mentioned a solution which I've tried to write out here:
def get_index(c, char_list):
return [index if c == char_list[index] else -1 for index in range(len(char_list))]
get_index(';', char_list)
# This returns a list equal to the length of char_list
# returns [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
# The else statement before -1 loops through the entire list and makes a list equal in length
# I want to just return [-1].
If I place the else statement at the very end of the list comprehension it raises and error.
How can I place an else statement in my list comprehension such that it would just return [-1] if the character passed in isn't present in the list and [index] if the char is present in the list. Is this possible?
This doesn't take into consideration that more than one count of a specific character could be present in the list. So in some regards it's kind of foolish to make it like this, but I'm interested in practicing list comprehensions