Home > Blockchain >  List Comprehension instead of a for loop not working
List Comprehension instead of a for loop not working

Time:11-26

Udemy course: Loop over the items of the passwords list and in each iteration print out the item if the item contains the strings 'ba' or 'ab' inside.

passwords = ['ccavfb', 'baaded', 'bbaa', 'aaeed', 'vbb', 'aadeba', 'aba', 'dee', 'dade', 'abc', 'aae', 'dded', 'abb', 'aaf', 'ffaec']

I know i could create the following for loop for this and it would work

for x in passwords:
    if 'ab' in x or 'ba' in x:
        print(x)

but I just learned about list comprehension so i tried making the following function to go over the loop instead.

def checker(passes):
    return (x for x in passes if 'ab' in x or 'ba' in x)

print(checker(passwords))

this doesn't work however and gives me this error : <generator object checker.. at 0x00000212414B4110> I have no clue what this means even after looking at my old friend google for help. \I dont understand why this function isn't working please help explain to me what I'm missing. I'm completely lost.

this is the expected outcome according to the answer hint

baaded
bbaa
aadeba
aba
abc
abb

CodePudding user response:

Even if that did work it wouldn't give you the results you desire. If you want to use that style you will have to join it.

def checker(passes):
    return '\n'.join(x for x in passes if 'ab' in x or 'ba' in x)
  • Related