1

I'm trying to store the vowels and constants indices of a string in two lists, so far I have the following:

def my_function(string):
    vowels_index = [] # vowels indices list
    const_index = [i if string[i] not in "AEIOU" else vowels_index.append(i) for i in range(len(string))] # constants indices list

Some None values are present in const_index:

>>> string = "BANANA"
>>> const_index = [i if string[i] not in "AEIOU" else vowels_index.append(i) for i in range(len(string))]
>>> const_index
[0, None, 2, None, 4, None]
>>>

Is there a better way to find the two lists?

  • 2
    Don't do that. `append` returns nothing, so you see a `None`. You have to have a new comprehension for vowels or other ways. – Austin Jun 08 '20 at 14:44
  • use a simple for loop insteadd of list comprehension, thanks me later, but as @Austin points out, you are adding the None returned when else – E.Serra Jun 08 '20 at 14:46
  • Also: [Why does append() always return None in Python?](https://stackoverflow.com/questions/16641119/why-does-append-always-return-none-in-python) – Georgy Jun 08 '20 at 14:47

1 Answers1

2

You can first use enumerate in a list comprehension to filter out the indices where a vowel occurs. Then you can use a set difference with all indices to find the complement which is where a consonant must occur.

def my_function(string):
    vowels = [idx for idx, val in enumerate(string) if val.lower() in 'aeiou']
    consts = list(set(range(len(string))) - set(vowels))
    return vowels, consts

>>> my_function('BANANA')
([1, 3, 5], [0, 2, 4])

Can unpack to get separate lists

>>> vowels, consts = my_function('BANANA')
>>> vowels
[1, 3, 5]
>>> consts
[0, 2, 4]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218