Home > Software design >  How do I write a loop that only prints 4 letter words from list? [closed]
How do I write a loop that only prints 4 letter words from list? [closed]

Time:09-23

Im very new to programming and Python in general.

Basically the title says it all. I have a list in python that looks like this:

names = ["Anna", "Ali", "Mike", "Jenna"]

How do I then write a loop that only prints the names with 4 letters in that list?

CodePudding user response:

Just need to perform an if check before printing, len() returns the length of something - in this case, a string:

for name in names:
    if len(name) == 4:
        print(name)

CodePudding user response:

Please check out this doc: https://www.w3schools.com/python/python_lists_loop.asp

for word in thislist:
   if len(word) == 4:
      print(word)

CodePudding user response:

Try this:

names = ["Anna", "Ali", "Mike", "Jenna"]
result = [name for name in names if len(name) == 4]
print(result)

Output:

['Anna', 'Mike']

CodePudding user response:

Or just:

>>> print('\n'.join(name for name in names if len(name)==4))
Anna
Mike
  • Related