Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : list comprehension + filter

I have a string from which I wish to extract vowels and consonants along with their indices.

I am thinking about :

a = "HELLO"
list_ = list(a)
vow = [(x, i) for i,x in enumerate(list_) if x in ['A', 'E', 'I', 'O', 'U']]
cons = [(x, i) for i, x in enumerate(list_) if x not in j for j in list_ if j in ['A', 'E', 'I', 'O', 'U']]

However, I am getting NameError (saying j is not defined). Why am I not able to nest my list comprehension.

My desired output :

vows : [('E', 1), ('O', 4)]
cons : [('H', 0), ('L', 2), ('L', 3)]
like image 388
Darshan Chaudhary Avatar asked May 19 '26 06:05

Darshan Chaudhary


1 Answers

The issue with your second list comprehension is that ideally the if condition should go at the end (after the second for loop , only then j would we accessible). But you really do not need that, simply check if x is not in the list of vowels. Example -

cons = [(x, i) for i,x in enumerate(list_) if x not in ['A', 'E', 'I', 'O', 'U']]

Demo -

>>> a = "HELLO"
>>> list_ = list(a)
>>> vow = [(x, i) for i,x in enumerate(list_) if x in ['A', 'E', 'I', 'O', 'U']]
>>> cons = [(x, i) for i,x in enumerate(list_) if x not in ['A', 'E', 'I', 'O', 'U']]
>>> vow
[('E', 1), ('O', 4)]
>>> cons
[('H', 0), ('L', 2), ('L', 3)]

You can make this a bit faster by using set for vowels and you do not really need list_ , you can enumerate over a itself, and get exactly same result. Example -

vowel_set = {'A', 'E', 'I', 'O', 'U'}
vow = [(x, i) for i,x in enumerate(a) if x in vowel_set]
cons = [(x, i) for i,x in enumerate(a) if x not in vowel_set]

Demo -

>>> a = "HELLO"
>>> vowel_set = {'A', 'E', 'I', 'O', 'U'}
>>> vow = [(x, i) for i,x in enumerate(a) if x in vowel_set]
>>> cons = [(x, i) for i,x in enumerate(a) if x not in vowel_set]
>>> vow
[('E', 1), ('O', 4)]
>>> cons
[('H', 0), ('L', 2), ('L', 3)]
like image 137
Anand S Kumar Avatar answered May 21 '26 23:05

Anand S Kumar