-1

Here is my explanation:

myList = ['Albasit', 'Nahian', 'Hi', 'Kazi', 'Zuljalal', 'Md.', 'Maslinia']

I want to search word in the list with their length. So that I can get the word which is 4 in len.

5 Answers5

1

Intuitively, you have two options. Filtering or a simple list comprehension.

myList = ['Albasit', 'Nahian', 'Hi', 'Kazi', 'Zuljalal', 'Md.', 'Maslinia']

list(filter(lambda x: len(x) == 4, myList))
# or
[x for x in myList if len(x) == 4]
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
0

Use a list comprehension:

print([x for x in myList if len(x) == 4])
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

You can create a new list filtering only the elements with len(element) == 4

myList = ['Albasit', 'Nahian', 'Hi', 'Kazi', 'Zuljalal', 'Md.', 'Maslinia']

new_list = [x for x in myList if len(x) == 4]

print(new_list)
>>> ['Kazi']
0
str_list = ["these", "are", "some", "random", "strings"]

for my_str in str_list:
    if len(my_str) == 3:
        print(my_str)

This will print out every 3 Letter word in the list. You can append these to a new list and then print the new list as well. Up to you.

Jax Teller
  • 163
  • 2
  • 18
  • 1
    Some tips: don't use types as variable names `str`, no need for extra parentheses in if-clauses, for-loops are mostly discouraged when list comprehensions are equivalent alternatives. – Bram Vanroy Nov 23 '20 at 09:11
  • @BramVanroy Thanks for the tips. I warn others about using types as variable names, yet do the same mistakes. Am not very experienced with list comprehensions. Will take a look. – Jax Teller Nov 23 '20 at 09:45
0
myList = ['Albasit', 'Nahian', 'Hi', 'Kazi', 'Zuljalal', 'Md.', 'Maslinia']

res = list(filter(lambda x: len(x) == 4, myList)) 
print(res) # ['Kazi']
Tasnuva Leeya
  • 2,515
  • 1
  • 13
  • 21
  • 2
    provide context to boost question quality. You're competing with 4 more for rep. EoR. – ZF007 Nov 23 '20 at 09:28