20

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

I have used :

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

to remove all entries that are under the length of 4. However, I do not want to remove the entries now. I want to create a new list with the words, but keeping them in the old list.

Perhaps something like this:

if len(word) == 9:
     newlist.append()
Georgy
  • 12,464
  • 7
  • 65
  • 73
MSA
  • 203
  • 1
  • 2
  • 4

4 Answers4

34

Sorry, realized you wanted length, 9, not length 9 or greater.

newlist = [word for word in words if len(word) == 9]
utdemir
  • 26,532
  • 10
  • 62
  • 81
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
3

Try:

newlist = []
for item in resultVital:
    if len(item) == 9:
        newlist.append(item)
BenjaminRH
  • 11,974
  • 7
  • 49
  • 76
2

try this:

newlist = [word for word in words if len(word) == 9]
David Wolever
  • 148,955
  • 89
  • 346
  • 502
Brian McFarland
  • 9,052
  • 6
  • 38
  • 56
  • Check the formatting hints on the bottom, right side of the edit page. Please format your code properly to make it easier to read. – S.Lott Sep 13 '11 at 18:14
0

Try this:

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