Python: create a new list from a list when a certain condition is met

I want to make a new list from another list of words; when a certain condition of a word is fulfilled. In this case, I want to add all the words of length 9 to the new list.

I used:

resultReal = [y for y in resultVital if not len(y) < 4] 

delete all records whose length is less than 4. However, I do not want to delete records now. I want to create a new list with words, but leave them in the old list.

Maybe something like this:

 if len(word) == 9: newlist.append() 

Thank you

+9
source share
4 answers

Sorry, I realized that you need a length of 9, not a length of 9 or more.

 newlist = [word for word in words if len(word) == 9] 
+21
source

Try:

  newlist = []
 for item in resultVital:
     if len (item) == 9:
         newlist.append (item) 
+2
source

try the following:

 newlist = [word for word in words if len(word) == 9] 
+1
source

Try this:

 list= [list_word for list_word in words if len(list_word) == 1] 
0
source

Source: https://habr.com/ru/post/897252/


All Articles