Skip to content
Advertisement

How do you separate a list into 2 based on what is in the list? [closed]

So I was given this list.

list = ["m2010","n1950","m1834","n993","m1490"]

I’d like to make the code separate the list into 2, which should look something like this:

n_list = ["n1950","n993"]

m_list = ["m2010","m1834","m1490"]

Everything that starts with “n” goes in the n_list and “m” in the m_list, but I’m too clueless to do it myslef…

Advertisement

Answer

list = ["m2010", "n1950", "m1834", "n993", "m1490"]

n_list = [item for item in list if item[0] == 'n']
m_list = [item for item in list if item[0] == 'm']
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement