Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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()
like image 916
MSA Avatar asked Sep 13 '11 18:09

MSA


People also ask

How do you create a list from a different list in Python?

Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete.

Can we create a list inside another list?

The items in the outer list are List<int> objects. In the first line, you create the outer list. In the second line, you create a list of int and add it as one of the items in the outer list. In the third line, you add an integer to the first inner list in the outer list.

How do I put one list into another list?

Use the extend() Method to Append a List Into Another List in Python. Python has a built-in method for lists named extend() that accepts an iterable as a parameter and adds it into the last position of the current iterable. Using it for lists will append the list parameter after the last element of the main list.


3 Answers

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

newlist = [word for word in words if len(word) == 9]
like image 53
g.d.d.c Avatar answered Sep 17 '22 22:09

g.d.d.c


Try:

newlist = []
for item in resultVital:
    if len(item) == 9:
        newlist.append(item)
like image 30
BenjaminRH Avatar answered Sep 18 '22 22:09

BenjaminRH


try this:

newlist = [word for word in words if len(word) == 9]
like image 29
Brian McFarland Avatar answered Sep 20 '22 22:09

Brian McFarland